反射

反射


####**反射:**   通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法。
  1. hasattr(obj,name_str): #检查成员
     判断对象obj里是否有对应字符串name_str的方法,存在为 true。
  2. getattr(obj,name_str): #获取成员
     根据字符串name_str去获取obj对象里对应方法的内存地址,如果name_str是静态方法则直接返回其值。
     因此可以用getattr(obj,func)()的方式调用func方法。
  3. setattr(obj,name_str,value): #设置成员
     等价于obj.name_str = value。
  4. delattr(obj,name_str): #删除成员

 反射是通过字符串的形式操作对象相关的成员。一切事物都是对象!!

用法一:增加方法,动态内存交配
def talk(self):
    print('%s is talking'%self.name)

class Student(object):
    def __init__(self,name):
        self.name = name
    def walk(self):
        print('%s is walking'%self.name)
s = Student('Tom')

choice = input('>>:').strip()   #choice = funk
if hasattr(s,choice):
    func = getattr(s,choice)
    func()
else:
    setattr(s,choice,talk)      #s.funk = talk
    s.funk(s)                   #s.talk(s)
    func = getattr(s,choice)    
    func(s)                     
---------------------------------------------
choice = funk
>>>:Tom is talking
>>>:Tom is talking
用法二:name_str是静态属性时
class Student(object):
    def __init__(self,name):
        self.name = name
    def walk(self,age):
        print('%s %s is walking'%(self.name,age))
s = Student('Tom')
choice = input(">>:").strip()
if hasattr(s,choice):
    func = getattr(s,choice)
    func()
else:
    setattr(s,choice,28)
    new = getattr(s,choice)
    print(new)
------------------------------------------------
choice = age
>>>:28

  可以看出,当我们需要执行对象里的某个方法,或需要调用对象中的某个变量,但是由于种种原因我们无法确定这个方法或变量是否存在时,我们就可以通过反射来进行处理,当然也可以通过反射,动态内存的分配来为类增加方法。

posted @ 2017-08-25 09:10  在下不想说  阅读(84)  评论(0编辑  收藏  举报