14、Python之反射
一、反射
反射的本质是:通过知道对象属性或方法的字符串形式,就能够访问该对象的属性和方法的过程。
1、检查对象是否有某个属性或方法,使用hasattr。
1 class Dog(object): 2 def __init__(self,name): 3 self._name = name 4 def bark(self): 5 print("%s is barking" % self._name) 6 7 d = Dog("lido") 8 print(hasattr(d,"bark")) #True - 有bark方法 9 print(hasattr(d,"bark1"))#False - 无bark1方法 10 print(hasattr(d,"_name"))#True - 有_name属性
2、通过属性或方法的字符串形式获得属性的值或方法的地址,使用getattr。
1 class Dog(object): 2 def __init__(self,name): 3 self._name = name 4 def bark(self): 5 print("%s is barking" % self._name) 6 7 d = Dog("lido") 8 bark_address = getattr(d,"bark")#通过bark的字符串返回其地址 9 bark_address() 10 name_01 = getattr(d,"_name") 11 print(name_01)
3、给对象动态添加属性或者方法,使用setattr
1 def run(name): 2 print("%s is running" % name) 3 4 class Dog(object): 5 def __init__(self,name): 6 self._name = name 7 def bark(self): 8 print("%s is barking" % self._name) 9 10 d = Dog("lido") 11 setattr(d,"_age",20) 12 setattr(d, 'run',run) 13 print(d._age) 14 d.run(d._name)
4、动态删除对象的属性或者方法,使用delattr。
1 class Dog(object): 2 def __init__(self,name): 3 self._name = name 4 def bark(self): 5 print("%s is barking" % self._name) 6 7 d = Dog("lido") 8 delattr(d,"bark") 9 delattr(d,"_name") 10 d.bark() 11 print(d._name)
5、如果只知道一个类的字符串形式,如何来创建类对象呢,方法有很多这里暂时先介绍一种,使用globals方法,这个方法返回一个字典,以类名的字符串作为key,地址作为value。代码如下:
1 class Dog(object): 2 def __init__(self,name): 3 self._name = name 4 def bark(self): 5 print("%s is barking" % self._name) 6 7 D = globals()["Dog"] 8 d = D("go") 9 d.bark()
6、综合实例
1 class Dog(object): 2 def __init__(self): 3 # self._name = name 4 pass 5 def bark(self): 6 print("%s is barking" % self._name) 7 def run(self): 8 print("%s is running" % self._name) 9 def sleep(self): 10 print("%s is sleeping" % self._name) 11 def print_self(self): 12 print("my name is %s" % self._name) 13 d = Dog() 14 setattr(d,"_name",input("请输入狗的姓名>>")) 15 while True: 16 choice = input("1、bark,1、run,3、sleep,4、print_selft") 17 if choice == '1': 18 break 19 if hasattr(d,choice): 20 getattr(d,choice)() 21 else: 22 print("输入错误")