首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >.method()和self.method()有什么区别?

.method()和self.method()有什么区别?
EN

Stack Overflow用户
提问于 2018-06-03 00:29:42
回答 1查看 1.1K关注 0票数 2

当我们从父类继承某些东西时,使用super().method()self.method()有什么不同?为什么要使用一个而不是另一个?

我唯一想到的就是使用静态方法调用self.method()显然是不可能的。至于其他事情,我想不出使用super()的理由。

当选择一个而不是另一个问题时,有人能提供一个虚拟的例子并解释为什么吗,或者这只是惯例的事情?

EN

回答 1

Stack Overflow用户

发布于 2018-06-03 00:34:16

super().method()将调用method的父类实现,即使子类定义了自己的父类也是如此。您可以阅读documentation for super以获得更深入的解释。

代码语言:javascript
复制
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的另一个实现,会调用哪个方法

代码语言:javascript
复制
class Grandchild(Child):
    def foo(self):
        print("Grandchild implementation")

g = Grandchild()
g.parent()
# Parent implementation
g.child()
# Grandchild implementation
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50658942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档