相关疑难解决方法(0)

何时调用Python的super().__ init __()?

(在谷歌搜索之后,我无法在任何地方找到参考资料.)

可以使用以下简短代码示例清楚地演示该场景:

class X:
    def __init__(self, stuff):
        self.__stuff = stuff

class Y(X):
    def __init__(self, stuff):
        # Is it safe to execute statements before calling super.__init__()?
        new_stuff = self.call_another_method(stuff)
        super(Y, self).__init__(new_stuff)
Run Code Online (Sandbox Code Playgroud)

使用CPython 3.x,上面的代码示例有效 - 假设call_another_method()存在.这种编码风格通常是安全的,但不赞成或被认为是unPythonic?我无法就此事找到建议.

我为什么在意?

我的背景来自更传统的面向对象编程语言,如C++,C#和Java,其中"super"必须严格地作为子类构造函数中的第一个语句调用 - 忽略零参数,隐式情况.

如果重要的话,我年轻的Pythoneer:3+,拜托.

python subclass super python-3.x

8
推荐指数
1
解决办法
2788
查看次数

标签 统计

python ×1

python-3.x ×1

subclass ×1

super ×1