python中有很多的内置函数,所谓内置函数,就是在python中被自动加载的函数,任何时候都可以用。内置函数,这意味着我们不必为了使用该函数而导入模块。不必做任何操作,Python 就可识别内置函数。在今后的学习中,不断地去学习这些内置函数。getattr(object,
name[, default])
官网上对getattr()函数的说明如下:Return the value of the named attribute of object. name must
be a string. If the string is the name of one of the object’s attributes, the
result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named
attribute does not exist, default is returned if provided, otherwise AttributeError is raised。
理解:根据给定的字符串name获得对象相应的属性或方法,例如getattr(x,'foobar')相当于x.foobar()。举个简单的实例说明:class attrtest(object):
def __init__(self,name):
self.name=name
def getattr1(self):
print(self.name)
print(getattr(self,'name'))
def attr(self,param):
print("attr is called and param is "+param)
def getattr2(self):
fun2=getattr(self,'attr')
fun2('crown')
if __name__=='__main__':
test=attrtest('test')
test.getattr1()
print ('getattr(self,\'name\') equals to self.name ')
test.getattr2()
print ('getattr(self,\'attr\') equals to self.attr ')
运行结果:test
test
getattr(self,'name') equals to self.name
test
test
getattr(self,'name') equals to self.name
attr is called and param is crown
getattr(self,'attr') equals to self.attr
getattr(self,'attr') equals to self.attr
从运行结果可以看出,在attrtest类中有一个变量name,当使用内置函数getattr(self,'name')相当于输出self.name,因此结果为test;同样,在第二个函数中getattr(self,'attr')相当于将self.attr()赋给了fun2,然后执行fun2('crown')就相当于执行self。attr('crown'),因此结果为attr is called and param is crown。
callable(object)
官网上说明:Return True if the object argument appears callable,
False if not. If this returns true, it is still
possible that a call fails, but if it is false, calling object will
never succeed. Note that classes are callable (calling a class returns a new
instance); instances are callable if their class has a __call__() method.
理解:检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。该函数在python2.x版本中都可用。但是在python3.0版本中被移除,而在python3.2以后版本中被重新添加。
例如我们在上面的例子中的getattr2()方法中添加判断方法是否可调用的语句:def getattr2(self):
fun2=getattr(self,'attr')
if callable(fun2):
fun2('crown')
当fun2可调用时执行fun2('crown').