getattr是python里的一个内建函数
getattr()这个方法最主要的作用是实现反射机制。也就是说可以通过字符串获取方法实例。这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时候动态加载。
python里面跟getattr相关的有hasattr,setattr,delattr ,那么我们通过下面的例子,来详细的说说他们的用法。
class Xiaorui:
def __init__(self):
self.name = 'xiaorui' def setName(self, name):
self.name = name def getName(self):
return self.name def greet(self):
print "Hello, i'm %s" % self.name foo = Xiaorui()
print hasattr(foo, 'setName')
一. hasattr(object,name)
判断object中是否具有name属性,例如:
print print hasattr(foo, 'setName') #判断setName是否存在,存在则返回True。
True
二. getattr(object,name,default)
如果存在name属性(方法)则返回name的值(方法地址)否则返回default值。
print getattr(foo, 'name', 'NA') #存在name属性,所以返回其value
xiaorui
print getattr(foo, 'age', 'NA')
NA
三. setattr(object,name,default)
setattr(foo,’age’,’18’) #字符串可能会列出一个现有的属性(或一个新的属性)。这个函数将值赋给属性的
setattr(foo, 'age', '18')
print getattr(foo, 'age', 'NA')
18
四. delattr(object,’name’)
delattr(foo,’name’)#删除属性name,原值为‘xiaorui’
delattr(foo, 'name')
print getattr(foo, 'name', 'not find')
not find