什么是反射?
通过字符串的形式操作对象相关属性。python中的事物都是对象;
关键方法:
(1)getattr:获取属性
(2)setattr:设置属性
(3)hashattr:检测是否含有属性,返回布尔值
(4)delattr:删除属性
具体功能演示:
class Foo: f = '类对静态变量' def __init__(self, name, age): self.name = name self.age = age def say_hi(self): print('hi, %s' % self.name) obj = Foo('xiaofei', 20) # 检测是否含有某属性 print(hasattr(obj, 'name')) print(hasattr(obj, 'say_hi')) # 执行结果: # True # True print('--------------------------------------') # 获取属性: print(getattr(obj, 'name')) func = getattr(obj, 'say_hi') func() print(getattr(obj, 'aaaaa', '不存在!')) # 执行结果: # xiaofei # hi, xiaofei # 不存在! print('--------------------------------------') # 设置属性 setattr(obj, 'gender', 'female') setattr(obj, 'show_name', lambda self: self.name + 'er') print(obj.gender) print(obj.show_name(obj)) # 执行结果: # female # xiaofeier print('--------------------------------------') # 删除属性 delattr(obj, 'age') delattr(obj, 'show_name') print(obj.__dict__) # 执行结果: # {'gender': 'female', 'name': 'xiaofei'} delattr(obj, 'aaaa') # 删除不存在对属性,会报错 实例中的用法: import os class Manage_cmd(object): def run(self): while True: cmd = input('>>>').strip() if not cmd: continue if hasattr(self, cmd): func = getattr(self, cmd) func() else: print('-bash: %s: command not found' % cmd) def ls(self): print(os.listdir('.')) cmd = Manage_cmd() cmd.run() # 执行结果: # >>>ls # ['test1.py'] # >>>asdfadf # -bash: asdfadf: command not found