class Parent:
def hello(self):
print("parent hello")
class Child(Parent):
def hello(self):
super().hello()
print("child hello")
这里:
super().hello()
更像 Java 的:
super.hello();
这是子类调用父类同名方法的标准写法。
8. Parent.hello(self) 和 super().hello() 有什么区别
先看:
class Parent:
def hello(self):
print("parent")
class Child(Parent):
def test1(self):
Parent.hello(self)
def test2(self):
super().hello()
这两种很多时候结果一样,但语义不同。
Parent.hello(self)
是说:
我明确指定调用
Parent这个类里的hello
super().hello()
是说:
按继承链规则,去找当前类的父类方法
这个在多继承里区别会很大。
所以一般推荐在继承体系里优先用 super()。
136



被折叠的 条评论
为什么被折叠?



