反射实现了动态的装配,通过字符串来反射类中的属性和方法
一、反射函数
1、hasarttr(obj,name_str)
判断一个对象obj中是否有对应的name_str字符串的属性或者方法
class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("{0}is eating {1}".format(self.name,food)) D = Dog("Bone") C = input(">>>:").strip() print(hasattr(D , C)) #obj中是否有对应的choice字符串的属性或者方法 #结果 >>>:name #输入对象存在属性 True >>>:eat #输入对象存在的方法 True
2、getattr(obj,name_str)
根据字符串name_str获取obj对象中的对应方法的内存地址或者对应属性的值
class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("{0}is eating {1}".format(self.name,food)) D = Dog("Bone") C = input(">>>:").strip() print(getattr(D , C)) #C获取obj对象中的对应方法的内存地址或者对应属性的值 # 结果 >>>:eat #返回eat方法的内存地址 <bound method Dog.eat of <__main__.Dog object at 0x10f611518>> >>>:name #返回name属性的值 Bone
3、setattr(x,y,z)
给obj对象添加一个新属性或者新方法,setattr(x, 'y', v) is equivalent to ``x.y = v''
①给对象新增一个新方法
def eat(self): print("{0} is eating".format(self.name)) class Dog(object): def __init__(self,name): self.name = name def drink(self,food): print("{0} is drinking {1}".format(self.name , food)) d = Dog("pengpeng") c = input(">>>:").strip() setattr(d,c,eat) #输入的是talk,所以又等同于d.talk = eat #d.talk(d) 直接写死,用d.talk(d),一般不这么写 func = getattr(d,c) #用getattr来获取 func(d) #结果 >>>:eat pengpeng is eating >>>:talk pengpeng is eating
②给对象新增一个属性
class Dog(object): def __init__(self,name): self.name = name def drink(self,food): print("{0} is drinking {1}".format(self.name , food)) d = Dog("pengpeng") c = input(">>>:").strip() setattr(d,c,18) #输入的是age,所以又等同于d.age = 18 print(getattr(d,c)) #结果 >>>:age 18
4、delattr(x,y)
删除obj对象中的属性或者方法,delattr(x, 'y') is equivalent to ``del x.y''
class Dog(object): def __init__(self,name): self.name = name def drink(self,food): print("{0} is drinking {1}".format(self.name , food)) d = Dog("pengpeng") c = input(">>>:").strip() delattr(d,c) #根据字符串删除属性或者方法 print(getattr(d,c)) print(d.name) print(d.drink) #结果 >>>:drink #删除方法drink Traceback (most recent call last): File "/Users/bianbian/PycharmProjects/test/71320h.py", line 9, in <module> delattr(d,c) #根据字符串删除属性或者方法 AttributeError: drink >>>:name #删除属性name Traceback (most recent call last): File "/Users/bianbian/PycharmProjects/test/71320h.py", line 10, in <module> print(getattr(d,c)) AttributeError: 'Dog' object has no attribute 'name'
5、综合使用hasattr、getattr、setattr
class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("{0} is eating {1}".format(self.name , food)) d = Dog("pengpeng") c = input(">>>:").strip() if hasattr(d,c): #判断d对象中存在属性和方法 name_value = getattr(d,c) #获取属性值 print(name_value) setattr(d,c,"bianbian") #修改属性值 print(getattr(d,c)) #重新获取属性的值 else: setattr(d,c,None) #设置不存在的属性值为None v = getattr(d,c) print(v) #结果 >>>:name pengpeng bianbian >>>:bb None