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

标签 python class initialization

在编写迷你游戏时,我偶然发现了一些我自己无法解释的东西(对 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 (normally self for instance methods, and cls for class methods).

关于python - super() 方法只初始化一些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58339901/

相关文章:

initialization - Redux 中的初始化状态问题为 "@@redux/init"

c++ - 为什么在此示例中出现错误 C2797?

javascript - 如何使用 javascript 在脚本文件或 views.py 中运行 python 函数而不加载页面

在不可变对象(immutable对象)中修改可变对象的Pythonic方式

C - 使用 strlen 使数组大小错误的数组初始化

c++ - 对对象使用 new

python - <类名>之间的区别。 python 类中的 <var name> 和 self.<var name>

python - 在 python 中逐行创建一个大数据集

python - PyParsing 前瞻和贪婪表达式

python - R 用户的 matplotlib?