当我们从父类继承某些东西时,使用super().method()
和self.method()
有什么不同?为什么要使用一个而不是另一个?
我唯一想到的就是使用静态方法调用self.method()
显然是不可能的。至于其他事情,我想不出使用super()
的理由。
当选择一个而不是另一个问题时,有人能提供一个虚拟的例子并解释为什么吗,或者这只是惯例的事情?
发布于 2018-06-03 00:34:16
super().method()
将调用method
的父类实现,即使子类定义了自己的父类也是如此。您可以阅读documentation for super
以获得更深入的解释。
class Parent:
def foo(self):
print("Parent implementation")
class Child(Parent):
def foo(self):
print("Child implementation")
def parent(self):
super().foo()
def child(self):
self.foo()
c = Child()
c.parent()
# Parent implementation
c.child()
# Child implementation
对于像Child
这样的单一继承类,super().foo()
与更显式的Parent.foo(self)
相同。在多重继承的情况下,super
将根据Method Resolution Order, or MRO确定要使用的foo
定义。
另一个振奋人心的例子是:如果我们子类化Child
并编写foo
的另一个实现,会调用哪个方法
class Grandchild(Child):
def foo(self):
print("Grandchild implementation")
g = Grandchild()
g.parent()
# Parent implementation
g.child()
# Grandchild implementation
https://stackoverflow.com/questions/50658942
复制相似问题