什么时候调用 Python 的 super().__init__()? [英] When to call Python's super().__init__()?

查看:31
本文介绍了什么时候调用 Python 的 super().__init__()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(在谷歌搜索后,我无法在任何地方找到有关此问题的参考.)

(I am unable to find a reference anywhere on this matter after some Googling.)

这个简短的代码示例可以清楚地展示这个场景:

The scenario can be clearly demonstrated with this short code sample:

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)

使用 CPython 3.x,上述代码示例有效——假设 call_another_method() 存在.这种编码风格通常是安全的,但不喜欢或被认为是非 Pythonic 的?我无法找到有关此问题的建议.

Using CPython 3.x, the above code sample works -- assuming call_another_method() exists. It this coding style generally safe, but frowned upon or considered unPythonic? I am unable to find advice on this matter.

我为什么在乎?

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

My background comes from more traditional object oriented programming languages such as C++, C#, and Java where "super" must be called strictly as the first statement in a subclass constructor -- ignoring the zero-argument, implicit case.

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

If it matters, I am a young Pythoneer: 3+, please.

推荐答案

是的,在 super() 之前调用其他东西是完全安全的.Python 不设置顺序,并且有很多用例.

Yes, it is perfectly safe to call other things before super(). Python doesn't set an order, and there are plenty of use-cases for this.

请注意,super().__init__() 调用只是 Python 中的另一个表达式,它不是语法结构.例如,您也可以在方法之外使用 super(),前提是您传入正确的参数.

Note that super().__init__() call is just another expression in Python, it is not a syntax construct. You can use super() outside methods too, for example, provided you pass in the right arguments.

在您的情况下,您可以省略类型和实例参数,当 super() 不带参数调用时,Python 3 会为您检索这些参数,因为您在内部定义的函数中使用它班级:

In your case, you can omit the type and instance arguments, Python 3 will retrieve these for you when super() is called without arguments, because you are using it in a function defined inside a class:

class Y(X):
    def __init__(self, stuff):
        new_stuff = self.call_another_method(stuff)
        # super(Y, self) is implicit here:
        super().__init__(new_stuff)

这篇关于什么时候调用 Python 的 super().__init__()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆