1 2 3 4 5 6 7 8 9 10 11 12 13
| class A: def f1(self): print("A.f1")
class B(A): def f1(self): print("B.f1")
b = B() b.f1()
------------ B.f1
|
上面的实例中,B类继承了A类,并重写了A类的f1方法,现在我想在B类中主动去调用父类中的方法,可以通过super
关键字实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class A: def f1(self): print("A.f1")
class B(A): def f1(self): super(B, self).f1() print("B.f1")
b = B() b.f1()
------------ A.f1 B.f1
|
应用场景:在源码中的某些功能不够完善,我们可以继承他的类,并在调用父类方法的情况下,在自己的类中添加一些功能。相当于在类中模拟了装饰器的功能
1 2 3 4 5 6 7 8 9 10
| class A: def f1(self): print("A.f1")
class B(A): def f1(self): print("装饰开始") ret = super(B, self).f1() print("装饰结束") return ret
|
非主流的方式去调用父类方法
1 2 3 4 5 6 7
| class A: def f1(self): print("A.f1")
class B(A): def f1(self): A.f1(self)
|