概念
運行時: 區別于編譯時,指程序被加載到內存中執行的時候.
反射(自省): 指運行時獲取對象的類型信息.
具有反射能力的函數:type(), isinstance(), getattr()等.
作用: 通過字符串映射或修改程序(內存)運行時的狀態、屬性、方法.
注意:對實例動態添加屬性時(setattr方法),注意該添加的方法不會綁定實例(使用時,相當于普通函數調用,參數需要填入).所以應該將方法添加到類對象中,而非該類對象的實例.
語法
a) ?hasattr(object,name)
判斷對象里是否有相應字符串的方法。如read里 輸入run方法。
print(hasattr(h, read))
b) ?getattr(object,name,default=None)
獲取字符串里的對象方法內存地址
print(getattr(h, read))# 映射對象的方法所在的內存地址
print(getattr(h, read)())# 加()執行對象方法
c) ?setattr(obj.name,value)
為對象創建新的方法(或將類之外的方法、屬性添加到類中)
obj.name = value
d) ?delattr(x,y)
刪除對象中的方法
例:利用反射使函數解耦
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()
例:利用反射,執行模塊方法
# 編寫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()