super() 方法只初始化一些参数

nha*_*aus 1 python initialization class

在编写小游戏时,我偶然发现了一些我自己无法解释的东西(对 Python 来说相当陌生)。这是我的代码:

class Block:
    def __init__(self, x, y, hitpoints=1, color=(255, 0, 0), width=75, height=35):
        self.color = color
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.hitpoints = hitpoints


class Ball(Block):
    def __init__(self, x, y, size, color=(255, 255, 255), velocity=1):
        super().__init__(self, x, y, color)
        self.velocity = velocity
        self.size = size
Run Code Online (Sandbox Code Playgroud)

我用

ball = Ball(x=200, y=200, size=30)

Run Code Online (Sandbox Code Playgroud)

当我调用 ball.x 时出现问题,因为它返回 <Objects.Ball object at 0x00000249425A3508>.

如果我调用 ball.y,它会按预期工作并返回 200。

我可以通过如下修改 Ball 类来解决整个问题:

class Ball(Block):
    def __init__(self,x, y, size, color=(255, 255, 255), velocity=1):
        super().__init__(self, y, color)
        self.velocity = velocity
        self.size = size
        self.x = x
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释为什么会发生这种情况吗?

非常感谢!

san*_*ash 5

您需要super不加self参数地调用:

super().__init__(x, y, color=color)
Run Code Online (Sandbox Code Playgroud)

这个 PEP解释了它是如何工作的:

新语法:

super()

相当于:

super(__class__, <firstarg>)

其中__class__是定义方法的类,是方法的第一个参数(通常self用于实例方法和cls类方法)。