日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python内置函数(57)——setattr

發布時間:2025/4/16 python 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。