【发布时间】:2019-12-31 02:00:28
【问题描述】:
python 中的 super() 内置函数的一个用例是调用一个被覆盖的方法。下面是一个使用super()调用Parent类的echo函数的简单例子:
class Parent():
def echo(self):
print("in Parent")
class Child(Parent):
def echo(self):
super().echo()
print("in Child")
我见过将 2 个参数传递给 super() 的代码。在这种情况下,签名看起来像super(subClass, instance),其中subClass 是调用super() 的子类,instance 是调用的实例,即self。所以在上面的例子中,super() 行会变成:
super(Child, self).echo()
查看python3 docs,这两个用例在从类内部调用时是相同的。
是否从 python3 开始完全弃用使用 2 个参数调用 super()?如果仅在调用重写函数时不推荐使用此方法,您能否举例说明为什么其他情况需要它们?
我也很想知道为什么 python 需要这两个参数?在 python3 中进行super() 调用时是否会注入/评估它们,还是在这种情况下不需要它们?
【问题讨论】:
标签: python python-3.x inheritance super