Python对象执行父类的方法

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):
# 主动执行父类的f1方法
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() # 接收父类f1方法执行结果的返回值
print("装饰结束")
return ret # 返回了父类f1执行结果的返回值(你可以自定义返回任何东西)

非主流的方式去调用父类方法

1
2
3
4
5
6
7
class A:
def f1(self):
print("A.f1")

class B(A):
def f1(self):
A.f1(self) # 别人这么写你需要看懂,但是自己不要这么写