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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. php網絡安全中命令執行漏洞的產生及本質探究2. 三個不常見的 HTML5 實用新特性簡介3. Angular獲取ngIf渲染的Dom元素示例4. IIS+PHP添加對webp格式圖像的支持配置方法5. ASP調用WebService轉化成JSON數據,附json.min.asp6. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁7. 使用.net core 自帶DI框架實現延遲加載功能8. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析9. php測試程序運行速度和頁面執行速度的代碼10. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析
