python反射的简单应用
class Cartoon(object): def __init__(self): self.name = "哪吒" def func(self): return "魔童降世" # 创建要操作的类的对象 obj = Cartoon() # 1. 查看属性 print(obj.name) # 2. 判断类中是否有该成员,当找到第二个参数时返回true,否则返回false have_1 = hasattr(obj, "func") have_2 = hasattr(obj, "drink") print(have_1) print(have_2) # 3. 获取对象的值. res_name = getattr(obj, "name") # 返回属实际性值. 如果没有此属性,程序报异常 # res_wrong1 = getattr(obj,"job") # 如果获取没有的属性或方法,会报错: AttributeError: 'Cartoon' object has no attribute 'job' res_method = getattr(obj, "func") # 返回方法的内存地址 r = res_method() # 执行方法 print(res_method) print(res_name) print(r) # 4. 设置属性值 res = setattr(obj, "name", "三太子") print(obj.name) # 5. 添加属性和值. 当设置的属性不存在时,会自动添加到属性和对应值到对象中 setattr(obj, "age", "3") # 相当于 obj.age = 3 print("name={0},age={1}".format(obj.name, obj.age)) # 6. 删除对象的属性 delattr(obj, "age") print(dir(obj)) # 查看大部分属性和方法. # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', # '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', # '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', # 'func', 'name'] #最后展示的是方法名和属性名