python getattr_Python中的getattr()函数详解:
標簽:Python中的getattr()函數詳解:
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.
解釋的很抽象 告訴我這個函數的作用相當于是
object.name
getattr(object,name)
其實為什么不用object.name而有的時候一定要用getattr(object,name),主要是由于這里的name有可能是變量,我們不知道這個name到底是什么,
只能用getattr(object,name)去獲得。
實例:
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 可以作用于 元組,但是由于元組沒有方法,所以不管你指定什么屬性名稱 ?getattr 都會引發一個異常。getattr()可以作用于
內置數據類型也可以作用于模塊。
getattr()三個參數,第一個是對象,第二個是方法,第三個是可選的一個缺省的返回值。如果第二個參數指定的屬性或方法沒找到則返回這個缺省
值。
getattr()作為一個分發者:
import statsout
def output(data,format=‘text‘):
output_function=getattr(statsout,‘output_%s‘%format,statsout.output_text)
return output_function(data)
標簽:
總結
以上是生活随笔為你收集整理的python getattr_Python中的getattr()函数详解:的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小班教案《认识动物》
- 下一篇: 怎样修改Mercury路由器密码路由器不