python - super().method() 和 self.method() 有什么区别

标签 python python-3.x

当我们从父类继承某些东西时,使用 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/

相关文章:

python - 如何在 docker 容器中设置 flask-socketio?

python - 无法在 vscode 中使用 jupyter 笔记本中的导入

python - 导入错误 : cannot import name '_counter' from 'Crypto.Util'

oracle - Pandas 通过 SQL Alchemy : UnicodeEncodeError: 'ascii' codec can't encode character 到 Oracle

python - 验证函数打印以前的输入而不是当前的

python - 将 boto 用于 AWS S3 Buckets for Signature V4

python - 如何禁用特定模块的日志记录

python - 如何获取数据框中的事件频率和每个事件的频率?

python-3.x - 你能举一个自适应步长 scipy.integrate.LSODA 函数的简单例子吗?

python - 为什么这段代码没有遍历所有 dict 的元素?