当我们从父类继承某些东西时,使用 super().method()
和 self.method()
有什么区别,为什么使用一个而不是另一个?
我唯一想到的是,使用静态方法显然不可能调用 self.method()
。至于其他一切,我想不出使用 super()
的理由。
有人可以在选择一项而不是另一项时提供一个虚拟示例并解释原因,还是这只是约定俗成的事情?
最佳答案
super().method()
将调用 method
的父类实现,即使 child 已经定义了自己的。您可以阅读 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
将确定哪个 foo
根据 Method Resolution Order, or MRO 使用的定义.
另一个激励性的例子:如果我们子类化 Child
会调用哪个方法并编写 foo
的另一个实现?
class Grandchild(Child):
def foo(self):
print("Grandchild implementation")
g = Grandchild()
g.parent()
# Parent implementation
g.child()
# Grandchild implementation
关于python - super().method() 和 self.method() 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50658942/