将类作为参数传入函数来修改类函数
将类作为参数传入函数来修改 (新增、覆盖) 类函数。
若将一个类作为参数传入一个函数,并在该函数中为该类添加一个函数,并且该函数与该类下的某个函数同名,则新添加的函数将覆盖原类中同名函数。
couter.py
from test.midd import middleFunc
class Couter1(object):
def __init__(self):
print('Couter1 __init__....')
def testone(self):
print('Couter1 testone....')
def nice(self):
print('Couter1 nice....')
middleFunc(Couter1) # 将类 Couter1 作为参数传入 middleFunc() 函数
from test.cinner import load_innerFunc
def middleFunc(obj):
load_innerFunc(obj)
def load_innerFunc(obj):
obj.testone = testone # 覆盖 Couter1 类中的 testone() 函数
obj.testha = testha # 为 Couter1 新增 testha() 函数
def testone():
print('innerFunc testone...')
def testha():
print('innerFunc testha...')
from test.couter import Couter1
if __name__ == '__main__':
c = Couter1()
# c.testone() # 调用原类中被覆盖方法,报错,已被覆盖
Couter1.testone() # 调用被覆盖方法
Couter1.testha() # 调用新增方法
# Couter1.nice() # 报错,不能直接通过类名调用
c.nice()
打印结果:
Couter1 init…
--------------11
innerFunc testone…
--------------22
innerFunc testha…
--------------33
Couter1 nice…