標籤:getattr 內建函數
python中有很多的內建函數,所謂內建函數,就是在python中被自動載入的函數,任何時候都可以用。內建函數,這意味著我們不必為了使用該函數而匯入模組。不必做任何操作,Python 就可識別內建函數。在今後的學習中,不斷地去學習這些內建函數。
官網上對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 ‘)
運行結果:
testtestgetattr(self,‘name‘) equals to self.name testtestgetattr(self,‘name‘) equals to self.name attr is called and param is crowngetattr(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。
官網上說明: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‘).