1.子类调用父类的方法,因此传入的self是<class ‘main.Child’>,因此,即使是在父类的方法中,子类的self调用的方法也是子类重写的方法
class Father():
def func(self):
print(self.__class__)
print("Father")
def test_father(self):
print("Test_father", self.__class__)
# 子类的self调用的方法也是子类重写的方法
self.func()
class Child(Father):
def func(self):
print(self.__class__)
print("Child")
def test_child(self):
# 子类的self是<class '__main__.Child'>
print("Test_child", self.__class__)
# 子类调用父类的方法
self.test_father()
if __name__ == '__main__':
tes_c = Child()
tes_c.test_child()
输出为:
Test_child <class '__main__.Child'>
Test_father <class '__main__.Child'>
<class '__main__.Child'>
Child
2.使用super调用父类的方法,self仍然是子类的,因此调用的就是子类重写的方法
class Father():
def __init__(self):
self.x = 10
def func(self):
print(self.__class__)
print("Father")
self.test()
def test(self):
print(self.x, self.__class__)
class Child(Father):
def __init__(self):
self.x = 100
# 调用父类的__init__重置self.x
super(Child, self).__init__()
def func(self):
print(self.__class__)
print("Child")
# 子类的self调用父类的方法
super().func()
def test(self):
print(self.x)
if __name__ == '__main__':
tes_c = Child()
tes_c.func()
输出为:
<class '__main__.Child'>
Child
<class '__main__.Child'>
Father
100