Python——反射 发表于 2018-10-25 | 分类于 Python入门 | | 阅读数 字数统计: 113 | 阅读时长 ≈ 1 反射反射指的是通过字符串来操作属性 123456789101112131415161718192021222324252627# e.g.class Foo: def __init__(self,name,age): self.name = name self.age = age def tell_info(self): print('%s:%s' %(self.name,self.age)) obj = Foo('ooc',18)# hasattrprint(hasattr(obj,'name')) # True# getattrprint(getattr(obj,'name')) # ooc# setattrsetattr(obj,'gender','male') # 增加属性print(obj.__dict__) # {'name': 'ooc', 'age': 18, 'sex': 'male'}stattr(obj,'name','david') # 已存在属性就修改属性print(obj.__dict__) # {'name': 'david', 'age': 18, 'sex': 'male'}# delattrdelattr(obj,'name')print(obj.__dict__) # {'age': 18, 'sex': 'male'}