英文文檔: setattr(object, name, value) This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may ...
英文文檔:
setattr
(object, name, value)
This is the counterpart of getattr()
. The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123)
is equivalent to x.foobar = 123
說明:
1. setattr函數和getattr函數是對應的。一個設置對象的屬性值,一個獲取對象屬性值。
2. 函數有3個參數,功能是對參數object對象,設置名為name的屬性的屬性值為value值。
>>> class Student: def __init__(self,name): self.name = name >>> a = Student('Kim') >>> a.name 'Kim' >>> setattr(a,'name','Bob') >>> a.name 'Bob'
3. name屬性可以是object對象的一個已經存在的屬性,存在的話就會更新其屬性值;如果name屬性不存在,則對象將創建name名稱的屬性值,並存儲value值。等效於調用object.name = value。
>>> a.age # 不存在age屬性 Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> a.age AttributeError: 'Student' object has no attribute 'age' >>> setattr(a,'age',10) # 執行後 創建 age屬性 >>> a.age # 存在age屬性了 10 >>> a.age = 12 # 等效於調用object.name >>> a.age 12