日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python getattr_Python中的getattr()函数详解:

發布時間:2023/12/2 python 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()函数详解:的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。