反射即想到4個內置函數分別爲:getattr,hasattr,setattr,delattr(獲取成員,檢查成員,設置成員,刪除成員)框架
下面逐一介紹:函數
1 class People: 2 country='China' 3 def __init__(self,name): 4 self.name=name 5 6 def eat(self): 7 print('%s is eating' %self.name) 8 9 peo1=People('egon') 10 11 12 # print(hasattr(peo1,'eat')) #peo1.eat 13 #檢查成員 14 # print(getattr(peo1,'eat')) #peo1.eat 15 # print(getattr(peo1,'xxxxx',None)) 16 #獲取成員 17 # setattr(peo1,'age',18) #peo1.age=18 18 # print(peo1.age) 19 #設置成員 20 # print(peo1.__dict__) 21 # delattr(peo1,'name') #del peo1.name 22 # print(peo1.__dict__)
23 # 刪除成員
對於反射小結:spa
1.根據字符串的形勢導入模塊code
2.根據字符串的形勢去對象(某個模塊)中操做其成員對象
實例:基於反射實現類Web框架的路由系統blog
實現思路:規定用戶輸入格式 模塊名/函數名 經過 hasattr和getattr 檢查並獲取函數返回值。ip
1 class Ftp: 2 def __init__(self,ip,port): 3 self.ip=ip 4 self.port=port 5 6 def get(self): 7 print('GET function') 8 9 def put(self): 10 print('PUT function') 11 12 def run(self): 13 while True: 14 choice=input('>>>: ').strip() 15 # print(choice,type(choice)) 16 # if hasattr(self,choice): 17 # method=getattr(self,choice) 18 # method() 19 # else: 20 # print('輸入的命令不存在') 21 22 method=getattr(self,choice,None) 23 if method is None: 24 print('輸入的命令不存在') 25 else: 26 method() 27 28 conn=Ftp('1.1.1.1',23) 29 conn.run()