python反射

概念

運行時: 區(qū)別于編譯時,指程序被加載到內存中執(zhí)行的時候.

反射(自省): 指運行時獲取對象的類型信息.

具有反射能力的函數(shù):type(), isinstance(), getattr()等.

作用: 通過字符串映射或修改程序(內存)運行時的狀態(tài)、屬性、方法.

注意:對實例動態(tài)添加屬性時(setattr方法),注意該添加的方法不會綁定實例(使用時,相當于普通函數(shù)調用,參數(shù)需要填入).所以應該將方法添加到類對象中,而非該類對象的實例.


語法

a) ?hasattr(object,name)

判斷對象里是否有相應字符串的方法。如read里 輸入run方法。

print(hasattr(h, read))

b) ?getattr(object,name,default=None)

獲取字符串里的對象方法內存地址

print(getattr(h, read))# 映射對象的方法所在的內存地址

print(getattr(h, read)())# 加()執(zhí)行對象方法

c) ?setattr(obj.name,value)

為對象創(chuàng)建新的方法(或將類之外的方法、屬性添加到類中)

obj.name = value

d) ?delattr(x,y)

刪除對象中的方法


例:利用反射使函數(shù)解耦

class New(object):

? ? def __init__(self):

? ? ? ? pass

? ? def input(self):

? ? ? ? while True:

? ? ? ? ? ? inp = input('>>> ')

? ? ? ? ? ? cmd = inp.split()[0]

? ? ? ? ? ? if hasattr(self,cmd):

? ? ? ? ? ? ? ? func = getattr(self,cmd)

? ? ? ? ? ? ? ? func(cmd)

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? print('{new} is not exist' .format(new=cmd))

? ? ? ? ? ? ? ? continue

? ? def inter(self,*args):

? ? ? ? x = args[0]

? ? ? ? print(x)

a1 = New()

a1.input()

例:利用反射,執(zhí)行模塊方法

# 編寫test2.py文件

def add():

? ?print('add')

def del_1():

? ?print('del')

def fetch():

? ?print('fetch')

# 編寫test1.py文件

import test2

list1 = [

? ?{'cap':'add user', 'func':'add'},

? ?{'cap':'del uesr', 'func':'del_1'},

? ?{'cap':'search user', 'func':'fetch'}

]

for index, item in enumerate(list1, 1):

? ?print(index, item['cap'])

def ch():

? ?choice = input('input num above menu: ')

? ?choice = int(choice)

? ?if choice in range(1,4):

? ? ? ?func_name = list1[choice-1]['func']

? ? ? ?func = getattr(test2, func_name)

? ? ? ?func()

? ?else:

? ? ? ?print('error! out of range!')

? ? ? ?return ch()

if __name__ == '__main__':

? ?ch()

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容