Python继承:调用父类方法

4
在Python 2中,调用从父类继承的方法有两种方式。使用super可以明确方法来自于父类,而不使用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()

输出:

Hello from Child
Hello from Parent
Hello from Parent

哪一个更好呢?我看到社区建议通过super进行调用,但是没有super的话调用会更简洁。

这个问题仅适用于Python 2。

1个回答

6
在您提供的情况下,从Child.hello内部调用super(Child, self).greet()是没有意义的。
通常只有在您需要调用与正在覆盖的方法相同的父类方法时才使用super
因此,在Child.hello中不需要使用super,因为您正在调用greet而不是父类的hello方法。
另外,如果存在父类方法Parent.hello,则可能希望从Child.hello中使用super调用它。但这取决于上下文和意图-例如,如果您想让子代略微修改父类的现有行为,则使用super可能是有意义的,但如果孩子完全重新定义了父类行为,则调用父级的超级方法可能没有意义,如果结果将被丢弃。通常最好保持安全,并调用超级类的方法,因为它们可能具有您希望子类保留的重要副作用。
另外值得一提的是,这适用于Python 2和3。 Python 3中唯一的区别是,由于不需要将父类和self作为参数传递给它,因此python 3中的超级调用更好。例如,在py3中,它只是super().greet(),而不是super(Parent,self).greet()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接