亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

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

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

瀏覽:5日期: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 編程
相關文章:
主站蜘蛛池模板: 精品一区中文字幕 | 538prom国产在线视频一区 | 国产黑丝视频在线观看 | 成人自拍小视频 | 很黄很色的小视频在线网站 | 国产日韩欧美一区二区三区在线 | 国产麻豆91网在线看 | 欧美性一区二区三区 | 国产一区二区三区在线 | 亚洲国产精品免费视频 | 直接看黄的网站 | 91视频大全| 美女被啪全免视频软件 | 免费一级欧美片片线观看 | 秘书上班和老板啪啪中文字幕 | 亚欧成人一区二区 | 亚洲精品久久久久中文字小说 | 亚洲国产精品久久久久婷婷老年 | 久久久久久久久综合影视网 | 国产福利小视频 | 激情婷婷综合 | 国产成人精品高清免费 | 日本vs欧美一区二区三区 | 国产高清一级毛片在线人 | 国产视频www | 免费观看很黄很色的大片 | 国产麻豆精品免费密入口 | 99视频在线看观免费 | 国产精品视频视频久久 | 香蕉亚洲精品一区二区 | 国产资源在线看 | 动漫chinesehdxxxx| 91精品亚洲 | 亚洲一级黄色毛片 | 亚洲国产精品久久精品成人 | 丝袜 亚洲 另类 欧美 变态 | 99视频精品全部国产盗摄视频 | 国产精品嫩草影院视频 | 午夜骚影 | 青草视频在线看 | 免费观看国产精品视频 |