內置函數getattr()
用於獲取指定對象的屬性值。在缺少屬性的情況下,它返回默認值。
**getattr(object, name[, default])** #Where object**,**name shows object name and attribute name respectively.
句法也像
object.name
getattr()
參數:
在參數的情況下,我們可以從控制台直接在程序中輸入屬性名。我們還可以設置一些默認值,以防屬性丟失,這使我們能夠完成一些不完整的數據。
參數 | 描述 | 必需/可選 |
---|---|---|
目標 | 要返回其命名屬性值的對象 | 需要 |
名字 | 包含屬性名稱的字符串 | 需要 |
系統默認值 | 找不到命名屬性時返回的值 | 可選擇的 |
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()
引發屬性錯誤
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'
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/249024.html