新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python getattr()
內置函數getattr()用于獲取指定對象的屬性值。在缺少屬性的情況下,它返回默認值。

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網綜合服務,包含不限于做網站、成都網站制作、硚口網絡推廣、小程序定制開發(fā)、硚口網絡營銷、硚口企業(yè)策劃、硚口品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學生創(chuàng)業(yè)者提供硚口建站搭建服務,24小時服務熱線:028-86922220,官方網址:www.cdcxhl.com
**getattr(object, name[, default])** #Where object**,**name shows object name and attribute name respectively.
句法也像
object.name
getattr()參數:
在參數的情況下,我們可以從控制臺直接在程序中輸入屬性名。我們還可以設置一些默認值,以防屬性丟失,這使我們能夠完成一些不完整的數據。
| 參數 | 描述 | 必需/可選 |
|---|---|---|
| 目標 | 要返回其命名屬性值的對象 | 需要 |
| 名字 | 包含屬性名稱的字符串 | 需要 |
| 系統(tǒng)默認值 | 找不到命名屬性時返回的值 | 可選擇的 |
getattr()返回值
getattr()函數的默認值選項有助于訪問不屬于該對象的任何屬性。
| 投入 | 返回值 | | 屬性 | 給定對象的命名屬性的值 | | 無屬性 | 缺省值 | | 如果找不到屬性并且沒有默認值 | AttributeError exception(屬性錯誤異常) |
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:找不到命名屬性時的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ā)屬性錯誤
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()
URL地址:http://www.5511xx.com/article/cdgddpd.html


咨詢
建站咨詢
