午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

您的位置:首頁技術文章
文章詳情頁

Python通過getattr函數獲取對象的屬性值

瀏覽:16日期:2022-07-08 09:36:42

英文文檔:

getattr(object, name[, default])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.

獲取對象的屬性值

說明:

1. 函數功能是從對象object中獲取名稱為name的屬性,等效與調用object.name。

#定義類Student>>> class Student: def __init__(self,name): self.name = name >>> s = Stduent(’Aim’)>>> getattr(s,’name’) #等效于調用s.name’Aim’>>> s.name’Aim’

2. 函數第三個參數default為可選參數,如果object中含義name屬性,則返回name屬性的值,如果沒有name屬性,則返回default值,如果default未傳入值,則報錯。

#定義類Student>>> class Student: def __init__(self,name): self.name = name>>> getattr(s,’name’) #存在屬性name’Aim’>>> getattr(s,’age’,6) #不存在屬性age,但提供了默認值,返回默認值6>>> getattr(s,’age’) #不存在屬性age,未提供默認值,調用報錯Traceback (most recent call last): File '<pyshell#17>', line 1, in <module> getattr(s,’age’)AttributeError: ’Stduent’ object has no attribute ’age’

與__getattr__的區別:

__getattr__是類的內置方法,當找不到某個屬性時會調用該方法;找到就不會調用.

getattr與類無關.

一個例子:作為data的代理類,可以以這種方式來使用data的屬性.

class DataProxy(...): def __getattr__(self, item): return getattr(self.data, item)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 成人午夜在线免费观看 | 国产一区二区三区视频 | 91丨国产 | 精品动漫一区二区三区 | 91精品久久久久久久 | 男人的伸进里面免费网站 | 亚洲h视频在线观看 | av天天在线| 成人免费公开视频 | 国产裸体永久免费无遮挡 | 亚洲天堂国产 | 在线观看视频亚洲 | 特黄特色大片免费播放器使用方法 | 免费毛片播放 | 欧美a∨| 日本大片在线播放 | 69国产| 天天爽爽| 久久99久| 精品一区二区三区在线观看 | 一二三四区在线 | 国产精品人成在线观看免费 | 国产精品h| 欧美亚洲91| 国产精品麻豆一区二区 | 国产成人精品久久 | 狠狠五月 | 精品玖玖玖 | 好吊色视频在线观看 | 久久婷婷激情 | wwwwww在线观看 | 69性视频 | 欧美黄页| 国产91一区 | 毛片最新网址 | 一级片高清 | 79av| 欧美午夜在线 | 亚洲日日日 | 久久精品影视 | 成年人的黄色 |