概念
運(yùn)行時(shí): 區(qū)別于編譯時(shí),指程序被加載到內(nèi)存中執(zhí)行的時(shí)候.
反射(自省): 指運(yùn)行時(shí)獲取對象的類型信息.
具有反射能力的函數(shù):type(), isinstance(), getattr()等.
作用: 通過字符串映射或修改程序(內(nèi)存)運(yùn)行時(shí)的狀態(tài)、屬性巍扛、方法.
注意:對實(shí)例動(dòng)態(tài)添加屬性時(shí)(setattr方法),注意該添加的方法不會(huì)綁定實(shí)例(使用時(shí),相當(dāng)于普通函數(shù)調(diào)用,參數(shù)需要填入).所以應(yīng)該將方法添加到類對象中,而非該類對象的實(shí)例.
語法
a) ?hasattr(object,name)
判斷對象里是否有相應(yīng)字符串的方法。如read里 輸入run方法。
print(hasattr(h, read))
b) ?getattr(object,name,default=None)
獲取字符串里的對象方法內(nèi)存地址
print(getattr(h, read))# 映射對象的方法所在的內(nèi)存地址
print(getattr(h, read)())# 加()執(zhí)行對象方法
c) ?setattr(obj.name,value)
為對象創(chuàng)建新的方法(或?qū)㈩愔獾姆椒ā傩蕴砑拥筋愔?
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()