反射就是經過字符串來操做類或者對象的屬性python
經過字符串來獲取,設置,刪除對象中的屬性或方法函數
class Foo: def __init__(self,name,pwd): self.name = name self.pwd = pwd def run(self): print('run') def speak(self): print('speak') p=Foo('xichen',18)
hasattr:判斷一個方法是否存在與這個類中code
print(hasattr(p,'name'))
True對象
getattr:根據字符串去獲取obj對象裏的對應的方法的內存地址,加"()"括號便可執行內存
if hasattr(p,cmd): run=getattr(p,cmd) run() else: print('該命令不存在')
請輸入命令:run字符串
runget
setattr:經過setattr將外部的一個函數綁定到實例中input
1.經過用戶輸入將外部的屬性添加到當前的實例中 print(p.__dict__) key=input('請輸入key:') value=input('輸入value:') setattr(p,key,value) print(p.__dict__)
{'name': 'xichen', 'pwd': 18}
請輸入key:age
輸入value:18
{'name': 'xichen', 'pwd': 18, 'age': '18'}cmd
2.動態的將外部的方法添加到當前的實例中 def test(a): print(a) print(p.__dict__) setattr(p,'test',test) print(p.__dict__) p.test(0)
{'name': 'xichen', 'pwd': 18}
{'name': 'xichen', 'pwd': 18, 'test': <function test at 0x000001D1E98069D8>}
0it
delattr:刪除一個實例或者類中的方法
1.最原始的刪除對象的屬性方法 print(p.__dict__) del p.name print(p.__dict__)
{'name': 'xichen', 'pwd': 18}
{'pwd': 18}
2.動態刪除p中屬性爲變量a的屬性 a=input('請輸入要刪除的屬性:') print(p.__dict__) delattr(p,a) print(p.__dict__)
請輸入要刪除的屬性:pwd # 刪除對象中屬性爲pwd字符串的屬性
{'name': 'xichen', 'pwd': 18}
{'name': 'xichen'}
判斷一下對象中有沒有沒有我輸入的屬性,若是有,打印
cmd=input('請輸入要查詢的屬性:') if hasattr(p,cmd): a=getattr(p,cmd) print(a) else: print('該屬性不存在')
請輸入要查詢的屬性:name xichen