將類作爲參數傳入函數來修改類函數
將類作爲參數傳入函數來修改 (新增、覆蓋) 類函數。
若將一個類作爲參數傳入一個函數,並在該函數中爲該類添加一個函數,並且該函數與該類下的某個函數同名,則新添加的函數將覆蓋原類中同名函數。
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…