super() 方法只初始化一些参数
super() method initializes only some parameters
在编写迷你游戏时,我偶然发现了一些我自己无法解释的东西(对 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 时出现问题,因为 returns
<Objects.Ball object at 0x00000249425A3508>
.
如果我调用 ball.y 它会按预期工作并且 returns 200.
我可以通过如下修改 class 球来解决整个问题:
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
有人可以向我解释为什么会这样吗?
非常感谢!
您需要在不带 self
参数的情况下调用 super
:
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 (normally self
for
instance methods, and cls
for class methods).
在编写迷你游戏时,我偶然发现了一些我自己无法解释的东西(对 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 时出现问题,因为 returns
<Objects.Ball object at 0x00000249425A3508>
.
如果我调用 ball.y 它会按预期工作并且 returns 200.
我可以通过如下修改 class 球来解决整个问题:
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
有人可以向我解释为什么会这样吗?
非常感谢!
您需要在不带 self
参数的情况下调用 super
:
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).