Python中的反射

反射即想到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 # 删除成员

对于反射小结:

1.根据字符串的形势导入模块

2.根据字符串的形势去对象(某个模块)中操作其成员

实例:基于反射实现类Web框架的路由系统

实现思路:规定用户输入格式 模块名/函数名 通过 hasattr和getattr 检查并获取函数返回值。

 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()
原文地址:https://www.cnblogs.com/huyingsakai/p/9243791.html