反射:通过字符串映射到对象的属性
class People: country = 'China' def __init__(self, name, age): self.name = name self.age = age def talk(self): print('%s is talking' %self.name) obj = People('egon', 18) print(obj.name) # obj.__dict__['name'] print(obj.talk) choice = input('>>:') # choice = 'name' print(obj.choice) # print(obj.'name') hasattr(obj, 'name') # 查找 obj.name 或 obj.__dict__['name'] 是否存在,返回True or False print(getattr(obj, 'name', None)) # 有的话返回方法或数据值 ,可设置默认值为None,在没有的情况下返回默认值None,不设置默认值会报错 setattr(obj, 'sex', 'male') # 修改 obj.sex = 'male' delattr(obj, 'age') # 删除 obj.age
反射的应用:通过输入,直接调用相应命令
class Service: def run(self): # 运行功能 while True: inp = input('>>:').strip() # inp = 'get a.txt' cmds = inp.split() # cmds = ['get','a.txt'] if hasattr(self, cmds[0]): func = getattr(self, cmds[0]) func(cmds) def get(self, cmds): # 下载功能 print('get...', cmds) def put(self, cmds): # 上传 print('put...', cmds) obj = Service() obj.run()