国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python通過(guò)getattr函數(shù)獲取對(duì)象的屬性值

瀏覽:4日期: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.

獲取對(duì)象的屬性值

說(shuō)明:

1. 函數(shù)功能是從對(duì)象object中獲取名稱(chēng)為name的屬性,等效與調(diào)用object.name。

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

2. 函數(shù)第三個(gè)參數(shù)default為可選參數(shù),如果object中含義name屬性,則返回name屬性的值,如果沒(méi)有name屬性,則返回default值,如果default未傳入值,則報(bào)錯(cuò)。

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

與__getattr__的區(qū)別:

__getattr__是類(lèi)的內(nèi)置方法,當(dāng)找不到某個(gè)屬性時(shí)會(huì)調(diào)用該方法;找到就不會(huì)調(diào)用.

getattr與類(lèi)無(wú)關(guān).

一個(gè)例子:作為data的代理類(lèi),可以以這種方式來(lái)使用data的屬性.

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 延边| 射阳县| 马鞍山市| 含山县| 自贡市| 马尔康县| 西平县| 河北区| 灵山县| 太和县| 安吉县| 乌拉特前旗| 印江| 寻乌县| 饶河县| 新建县| 墨脱县| 仪陇县| 怀集县| 万盛区| 广宗县| 抚远县| 邢台市| 镇原县| 马关县| 永和县| 崇义县| 务川| 尼勒克县| 益阳市| 汝南县| 峨山| 隆安县| 贵州省| 樟树市| 桐城市| 东海县| 宜丰县| 沅江市| 陵川县| 科技|