新聞中心
內(nèi)置函數(shù)getattr()用于獲取指定對(duì)象的屬性值。在缺少屬性的情況下,它返回默認(rèn)值。

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于做網(wǎng)站、成都網(wǎng)站制作、硚口網(wǎng)絡(luò)推廣、小程序定制開發(fā)、硚口網(wǎng)絡(luò)營(yíng)銷、硚口企業(yè)策劃、硚口品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供硚口建站搭建服務(wù),24小時(shí)服務(wù)熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com
**getattr(object, name[, default])** #Where object**,**name shows object name and attribute name respectively.
句法也像
object.name
getattr()參數(shù):
在參數(shù)的情況下,我們可以從控制臺(tái)直接在程序中輸入屬性名。我們還可以設(shè)置一些默認(rèn)值,以防屬性丟失,這使我們能夠完成一些不完整的數(shù)據(jù)。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 目標(biāo) | 要返回其命名屬性值的對(duì)象 | 需要 |
| 名字 | 包含屬性名稱的字符串 | 需要 |
| 系統(tǒng)默認(rèn)值 | 找不到命名屬性時(shí)返回的值 | 可選擇的 |
getattr()返回值
getattr()函數(shù)的默認(rèn)值選項(xiàng)有助于訪問不屬于該對(duì)象的任何屬性。
| 投入 | 返回值 | | 屬性 | 給定對(duì)象的命名屬性的值 | | 無屬性 | 缺省值 | | 如果找不到屬性并且沒有默認(rèn)值 | AttributeError exception(屬性錯(cuò)誤異常) |
Python 中getattr()方法的示例
示例getattr()在 Python 中是如何工作的?
class Person:
age = 30
name = "James"
pers = Person()
print('The age is:', getattr(pers, "age"))
print('The age is:', pers.age)
輸出:
The age is: 30
The age is: 30示例 2:找不到命名屬性時(shí)的getattr()
class Person:
age = 30
name = "James"
pers = Person()
# when default value is provided
print('The sex is:', getattr(pers, 'sex', 'Male'))
# when no default value is provided
print('The sex is:', getattr(pers, 'sex'))
輸出:
The sex is: Male
AttributeError: 'Person' object has no attribute 'sex'示例 3:getattr()引發(fā)屬性錯(cuò)誤
class GfG :
name = "GeeksforGeeks"
age = 24
# initializing object
obj = GfG()
# use of getattr
print("The name is " + getattr(obj,'name'))
# use of getattr with default
print("Description is " + getattr(obj, 'description' , 'CS Portal'))
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))
輸出:
The name is GeeksforGeeks
Description is CS Portal
AttributeError: GfG instance has no attribute 'motto' 文章名稱:創(chuàng)新互聯(lián)Python教程:Python getattr()
本文來源:http://www.dlmjj.cn/article/cdgddpd.html


咨詢
建站咨詢
