內置函數setattr()
用于將給定值賦給指定對象的指定屬性。
**setattr(object, name, value)** #where object indicates whose attribute value is needs to be change
setattr()
參數:
取三個參數。我們可以說setattr()
相當于 object.attribute = value。
參數 | 描述 | 必需/可選 |
---|---|---|
目標 | 必須設置其屬性的對象 | 需要 |
名字 | 屬性名 | 需要 |
價值 | 該值被賦予該屬性 | 需要 |
setattr()
返回值
setattr()
方法不返回任何東西,它只分配對象屬性值。這個函數在動態編程中很有用,在這種情況下,我們不能使用“點”運算符來分配屬性值。
Python 中setattr()
方法的示例
示例setattr()
在 Python 中是如何工作的?
class PersonName:
name = 'Dany'
p = PersonName()
print('Before modification:', p.name)
# setting name to 'John'
setattr(p, 'name', 'John')
print('After modification:', p.name)
輸出:
Before modification: Dany
After modification: John
示例 2:當在setattr()
中找不到屬性時
class PersonName:
name = 'Dany'
p = PersonName()
# setting attribute name to John
setattr(p, 'name', 'John')
print('Name is:', p.name)
# setting an attribute not present in Person
setattr(p, 'age', 23)
print('Age is:', p.age)
輸出:
Name is: John
Age is: 23
示例 3: Python setattr()
異常情況
class PersonName:
def __init__(self):
self._name = None
def get_name(self):
print('get_name called')
return self._name
# for read-only attribute
name = property(get_name, None)
p = PersonName()
setattr(p, 'name', 'Sayooj')
輸出:
Traceback (most recent call last):
File "/Users/sayooj/Documents/github/journaldev/Python-3/basic_examples/python_setattr_example.py", line 39, in <module>setattr(p, 'name', 'Sayooj')
AttributeError: can't set attribute</module>