Python内置函数(57)——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.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?
轉載于:https://www.cnblogs.com/sesshoumaru/p/6063893.html
總結
以上是生活随笔為你收集整理的Python内置函数(57)——setattr的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅谈JavaScript 函数作用域当中
- 下一篇: 作业八总结