python - __init__() 得到意外的关键字参数 'y'

标签 python pygame livewires

我正在阅读《绝对初学者的 Python 编程》一书,并决定通过制作自己的游戏来测试我的一些技能。这个游戏基本上是“不要被飞行的尖刺击中”,我遇到了一个问题。使用此代码运行它时:

class Player(games.Sprite):
    """The player that must dodge the spikes."""

    def update(self):
        """Move to the mouse."""
        self.x = games.mouse.x
        self.y = games.mouse.y
        self.check_collide()

    def check_collide(self):
        """Check for a collision with the spikes."""
        for spike in self.overlapping_sprites:
            spike.handle_collide()


def main():


    pig_image = games.load_image("Mr_Pig.png")
    the_pig = Player(image = pig_image,
                     x = games.mouse.x,
                     y = games.mouse.y)
    games.screen.add(the_pig)
    games.mouse.is_visible = False
    games.screen.event_grab = True

    games.screen.mainloop()

main()

我没问题。但是当我想使用“init”时,如以下代码所示:

class Player(games.Sprite):
    """The player that must dodge the spikes."""

    def update(self):
        """Move to the mouse."""
        self.x = games.mouse.x
        self.y = games.mouse.y
        self.check_collide()

    def check_collide(self):
        """Check for a collision with the spikes."""
        for spike in self.overlapping_sprites:
            spike.handle_collide()

    def __init__(self):
        """A test!"""
        print("Test.")


def main():

    pig_image = games.load_image("Mr_Pig.png")
    the_pig = Player(image = pig_image,
                     x = games.mouse.x,
                     y = games.mouse.y)
    games.screen.add(the_pig)
    games.mouse.is_visible = False
    games.screen.event_grab = True

    games.screen.mainloop()

main()

运行游戏时出现此错误:

File "run.py", line 85, in main
    y = games.mouse.y)
TypeError: __init__() got an unexpected keyword argument 'y'.

最佳答案

这一行:

the_pig = Player(image = pig_image,
                 x = games.mouse.x,
                 y = games.mouse.y)

(某种程度上)相当于:

the_pig = Player.__init__(image = pig_image,
                 x = games.mouse.x,
                 y = games.mouse.y)

这意味着您的 __init__ 应该接受参数 imagexy,但您已经定义了它如:

def __init__(self):
    """A test!"""
    print("Test.")

如果你想简单地传递所有参数,你可以这样做:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    """A test!"""
    print("Test.")

这使用 * and **语法来获取所有参数和关键字参数,然后使用 super使用这些参数调用父类(super class) __init__

替代方案(更多工作)是:

def __init__(self, image, x, y):
    super().__init__(image=image, x=x, y=y)
    """A test!"""
    print("Test.")

关于python - __init__() 得到意外的关键字参数 'y',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274346/

相关文章:

python - Python中的lambda表达式内的赋值

python - Pandas DataFrame 到 Numpy 数组 ValueError

python - Pygame 碰撞错误

python - 来自 Pandas 的 NTILE for Sqlite 给出操作错误

python - 如何在达到特定情况时停止pygame中的计时器

没有 Pygame 的 Python 游戏设计

Python livewires 调整屏幕大小

python - 有没有办法在运行 pygame 的同时也可以运行控制台?

Python、Pygame、Livewires - 如何进行平滑的碰撞?

python - 如何按增量连接时间/整数间隔?