Nar*_*sim 4 python inheritance python-2.7
在Python 2中,有两种方法可以调用从父类继承的方法。with superwhere 明确表明这些方法来自父类,而没有super.
class Parent(object):
def greet(self):
print('Hello from Parent')
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
def hello(self):
print('Hello from Child')
self.greet()
super(Child, self).greet()
child = Child()
child.hello()
Run Code Online (Sandbox Code Playgroud)
输出:
Hello from Child
Hello from Parent
Hello from Parent
Run Code Online (Sandbox Code Playgroud)
哪一个是首选?我看到社区建议通过 进行调用super,但如果没有 super ,调用会更加简洁。
该问题仅适用于 Python 2。
在您给出的上下文中,super(Child, self).greet() 从 inside Child.hello调用是没有意义的。
通常,您应该只调用super与您所在的重写方法同名的父类方法。
因此不需要superin Child.hello,因为您正在调用greet而不是父类的hello方法。
此外,如果有一个父方法Parent.hello,那么您可能希望使用 super 从内部调用它Child.hello。但这取决于上下文和意图 - 例如,如果您希望子级稍微修改父级的现有行为,那么使用 super 可能是有意义的,但如果子级完全重新定义了父类的行为,则调用 super 可能没有意义父级的 super 方法,如果结果将被丢弃。不过,为了安全起见,通常最好调用超类的方法,因为它们可能会产生您希望子类保留的重要副作用。
还值得一提的是,这适用于 python 2 和 3。Python 3 中的唯一区别是 super 调用在 python 3 中更好一些,因为您不需要将父类和 self 作为参数传递给它。例如,在 py3 中,它只是super().greet()而不是super(Parent, self).greet().