【问题标题】:How do I fix TypeError: __init__() missing 1 required positional argument: 'y'如何修复 TypeError:__init__() 缺少 1 个必需的位置参数:'y'
【发布时间】:2021-12-17 12:02:32
【问题描述】:

我目前正在尝试为我的角色设置碰撞箱,但我似乎无法摆脱这个错误。

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        pygame.sprite.Sprite.__init__(self)
        self.image = IronMan
        self.rect = self.image.get_rect()
        self.rect.y = 475
        self.direction = 1
        self.hitbox = (self.x + 20, self.y + 11, 28, 60)

    def draw(self, win):
        self.hitbox = (self.x + 20, self.y + 11, 28, 60)
        pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)
                       

当代码运行时,我面临着

TypeError: __init__() missing 1 required positional argument: 'y'

【问题讨论】:

  • full 错误信息是什么?您如何尝试实例化您的 Player
  • 您只包含您的定义。我们需要查看您调用__init__() 的那一行,它应该类似于variable_name = Player(x_value,y_value)
  • 您可能没有将“y”参数传递给 __init__()。找到你实例化这个类的行并为 y 写一个值

标签: python typeerror


【解决方案1】:

看起来您在创建类的实例时没有提供足够的参数。有 2 个选项可以修复它。

  1. 创建实例时提供足够的参数。

例子:

Mark = Player() # Error
Cindy = Player(1) # Error
James = Player(1, 2) # Good!

由于您指定 _init_ 方法接受 2 个参数,因此在调用它时必须提供 2 个参数。

  1. 只需为参数设置一个默认值。 您可以使用“=”号来做到这一点。

例子:

def __init__(self, x=0, y=0):
    #blabla

现在,_init_ 方法会自动将参数初始化为 0(如果未手动提供)。

Mark = Player() # Mark.x=0, Mark.y=0
Cindy = Player(1) # Cindy.x=1, Cindy.y=0
James = Player(1, 2) # James.x=1, James.y=2

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 2021-06-05
    • 1970-01-01
    • 2022-06-11
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多