012-將類作爲參數傳入函數來修改函數方法

將類作爲參數傳入函數來修改類函數


將類作爲參數傳入函數來修改 (新增、覆蓋) 類函數。

若將一個類作爲參數傳入一個函數,並在該函數中爲該類添加一個函數,並且該函數與該類下的某個函數同名,則新添加的函數將覆蓋原類中同名函數。
在這裏插入圖片描述
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() 函數

midd.py

from test.cinner import load_innerFunc

def middleFunc(obj):
    load_innerFunc(obj)

cinner.py

def load_innerFunc(obj):
    obj.testone = testone	# 覆蓋 Couter1 類中的 testone() 函數
    obj.testha = testha		# 爲 Couter1 新增 testha() 函數

def testone():
    print('innerFunc testone...')

def testha():
    print('innerFunc testha...')

test.py

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…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章