python getattr_Python中的getattr()函数详解:
標(biāo)簽:Python中的getattr()函數(shù)詳解:
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, ‘y‘) is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn‘t
exist; without it, an exception is raised in that case.
解釋的很抽象 告訴我這個(gè)函數(shù)的作用相當(dāng)于是
object.name
getattr(object,name)
其實(shí)為什么不用object.name而有的時(shí)候一定要用getattr(object,name),主要是由于這里的name有可能是變量,我們不知道這個(gè)name到底是什么,
只能用getattr(object,name)去獲得。
實(shí)例:
def info(object,spacing=10,collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList=[method for method in dir(object) if callable(getattr(object,method))]
processFunc=collapse and (lambda s: ‘‘.join(s.split())) or (lambda s:s)
print "\r\n".join(["%s%s"%(method.ljust(spacing),processFunc(str(getattr(object,method).__doc__)))for method in methodList])
if __name__==‘__main__‘:
print info.__doc__
print info([])
理論上, getattr 可以作用于 元組,但是由于元組沒(méi)有方法,所以不管你指定什么屬性名稱 ?getattr 都會(huì)引發(fā)一個(gè)異常。getattr()可以作用于
內(nèi)置數(shù)據(jù)類型也可以作用于模塊。
getattr()三個(gè)參數(shù),第一個(gè)是對(duì)象,第二個(gè)是方法,第三個(gè)是可選的一個(gè)缺省的返回值。如果第二個(gè)參數(shù)指定的屬性或方法沒(méi)找到則返回這個(gè)缺省
值。
getattr()作為一個(gè)分發(fā)者:
import statsout
def output(data,format=‘text‘):
output_function=getattr(statsout,‘output_%s‘%format,statsout.output_text)
return output_function(data)
標(biāo)簽:
總結(jié)
以上是生活随笔為你收集整理的python getattr_Python中的getattr()函数详解:的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 小班教案《认识动物》
- 下一篇: python登录页面_Python:简单