在编写迷你游戏时,我偶然发现了一些我自己无法解释的东西(对 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
我用初始化对象球
ball = Ball(x=200, y=200, size=30)
当我调用 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
有人可以向我解释为什么会这样吗?
非常感谢!
最佳答案
您需要调用super
没有self
参数:
super().__init__(x, y, color=color)
This PEP解释这是如何工作的:
The new syntax:
super()
is equivalent to:
super(__class__, <firstarg>)
where
__class__
is the class that the method was defined in, and is the first parameter of the method (normallyself
for instance methods, andcls
for class methods).
关于python - super() 方法只初始化一些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58339901/