python反射
2018-07-23 本文已影响0人
奔跑的老少年
我们可通过反射添加、修改、删除某个对象的属性和方法:
hasattr(object,str):判断该对象是否含有该方法或属性
getattr(object,str):拿到这个对象的方法或属性,若是属性,直接返回属性值,若是方法则返回内存地址
setattr(object,str,value):修改属性值或新增属性值或新增方法
def bulk(self):
print('%s is yelling'% self.name)
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print('%s is eating'% self.name,food)
d = Dog('QQ')
choice = input('put method>>:').strip()
# print(hasattr(d,choice)) #put method>>:eat 执行结果True
# print(getattr(d,choice)) #put method>>:eat 如果get的是一个对象,就将内存地址返回,如果是一个静态属性,就将属性值返回
if hasattr(d,choice):#判断d 对象是否有choice这个方法或属性
delattr(d,choice)#删除某个属性或方法
func = getattr(d,choice)#拿到choice这个方法或属性,若是属性直接返回
# func('baozi')#若是方法传值调用
print(func)#打印属性
setattr(d,choice,'kk')#修改该属性值
else:
# setattr(d,choice,bulk) #动态添加一个没有的方法,相当于d.choice = bulk
# func = getattr(d,choice)
# func(d) #不可直接d.bulk,bulk并不是d中的一个方法
setattr(d,choice,22)#动态添加一个没有的属性,值为22
print(getattr(d,choice))
print(d.name)