python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,该四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。
hasattr(obj,name_str):判断一个对象obj里是否有name_str字符串对应的的方法或者属性
getattr(obj,name_str):相当于obj.name_str,根据字符串去获取obj对象里对应的方法的内存地址或对应属性的值
setattr(x, 'y', v) :相当于``x.y = v'',即通过字符串设置新的属性或方法
delattr(x, 'y'):相当于``del x.y'',删除对象obj里y字符串对应的属性

class Foo(object): def __init__(self): self.name = 'wupeiqi' def func(self): return 'func' obj = Foo() # #### 检查是否含有成员 #### hasattr(obj, 'name') hasattr(obj, 'func') # #### 获取成员 #### getattr(obj, 'name') getattr(obj, 'func') # #### 设置成员 #### setattr(obj, 'age', 18) setattr(obj, 'show', lambda num: num + 1) # #### 删除成员 #### delattr(obj, 'name') delattr(obj, 'func')
反射代码示例2:
#Author:Zheng Na def bulk(self): #外部方法 print("%s is yelling..." % self.name) class Dog(object): def __init__(self,name,age): self.name = name self.age = age def eat(self): print("%s is eating..." %self.name) d = Dog("小黄",1) choice = input("请输入属性或方法>>:").strip() if choice == "name": # 判断对象中是否有字符串对应的属性 print(hasattr(d,choice)) # true # 根据字符串去对象中获取对应属性的值 attr = getattr(d,choice) print(attr) # 小黄 # 修改对象中字符串对应属性的值 setattr(d,choice,"小白") print(d.name) # 小白 # 删除对象中字符串对应的属性 delattr(d,choice) print(d.name) # 报错:AttributeError: 'Dog' object has no attribute 'name' elif choice == "eat": # 判断对象中是否有字符串对应的方法 print(hasattr(d, choice)) # true # 据字符串去获取obj对象里对应的方法的内存地址,然后调用这个方法 func = getattr(d,choice) func() # 小黄 is eating... # 方法不能删除?还是我的用法有错? # delattr(d, choice) # 报错:AttributeError: eat elif choice == "talk": # 通过字符串设置新的方法,可动态地将一个外部的方法装配到类里 # bulk现在相当于一个变量名,你现在用talk来代替了 # 1.方法写死 # setattr(d,choice,bulk) # d.talk(d) # 小黄 is yelling... # 2.方法不写死 setattr(d,choice,bulk) func = getattr(d,choice) func(d) # 小黄 is yelling... else:# choice输入money # 通过字符串设置新的属性 setattr(d, choice, 22) print(getattr(d,choice)) # 22
3种方式获取obj对象中的name变量指向内存中的值 “alex”
class Foo(object): def __init__(self): self.name = 'alex' def func(self): return 'func' # 不允许使用 obj.name obj = Foo() print(obj.name) print(getattr(obj, 'name')) print(obj.__dict__['name'])