python 反射

通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法

1.hasattr(对象名,属性或方法名):

判断object中有没有一个name字符串对应的方法或属性
class dog(object):
    '''hasattr方法是判断类中是否有指定的方法'''
    def __init__(self,name):
        self.name=name
    def eat(self):
        print '%s is ....'%self.name
d=dog('xx')
c=raw_input('---:')
# e=''.join(c)
print (hasattr(d, c))   #hasattr(对象名,属性名)

结果:
---:eat
True

2.getattr(对象名, 方法名):返回对象中方法在内存中的地址

class dog(object):
    
    def __init__(self,name):
        self.name=name
    def eat(self):
        print '%s is ....'%self.name
d=dog('xx')
c=raw_input('---:')
# e=''.join(c)
print (hasattr(d, c))   #hasattr(对象名,属性名)
print getattr(d, c)   #返回方法在内存中的地址
getattr(d, c)()    #eat()

结果:
---:eat
True
<bound method dog.eat of <__main__.dog object at 0x02376AB0>>
xx is ....

3.setattr(对象名,字符串,方法名);将类定义之外的方法可以被实例化对象使用,将方法名赋值给对象名.字符串。

class dog(object):
    '''setattr方法是将类之外的方法可以被实例化对象使用'''
    def __init__(self,name):
        self.name=name
    def eat(self):
        print '%s is ....'%self.name
def bul(self):
    print "bul....%s..."%self.name

d=dog('xx')
c=raw_input('---:')
setattr(d,c,bul)  #d.c=bul  将方法名赋予d.c
p=getattr(d, c)   #得到方法bul的内存地址
p(d)    #使用方法bul  ,也可以这样写d.ta(d)

结果:
---:ta
bul....xx...

4. delattr删除类中指定的方法或属性

class dog(object):
    '''delattr删除类中的方法或属性'''
    def __init__(self,name):
        self.name=name
    def eat(self):
        print '%s is ....'%self.name

d=dog('xx')
c=raw_input('---:')
delattr(d,c )  #删除指定的方法或属性
print d.name

结果:
---:name
Traceback (most recent call last):
  File "D:\soft\eclipse-workspace\ceshi\lianx1.py", line 540, in <module>
    print d.name
AttributeError: 'dog' object has no attribute 'name'

  

 

posted @ 2018-06-20 22:44  python|一路向前  阅读(295)  评论(0编辑  收藏  举报