Python使用內置函數setattr設置對象的屬性值
英文文檔:
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.ageAttributeError: ’Student’ object has no attribute ’age’>>> setattr(a,’age’,10) # 執行后 創建 age屬性>>> a.age # 存在age屬性了10>>> a.age = 12 # 等效于調用object.name>>> a.age12
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: