測試環境為 CentOS 8 x86_64 (虛擬機)
Python 的內建函式 – https://docs.python.org/zh-tw/3.11/library/functions.html 下面來看一下針對 object 的 getattr() , setattr() , hasattr() 與 delattr()
- hasattr(object, name)
The result is True if the string is the name of one of the object’s attributes, False if not. - getattr(object, name[, default])
Return the value of the named attribute of object. - setattr(object, name, value)
The function assigns the value to the attribute, provided the object allows it. - delattr(object, name)
The function deletes the named attribute, provided the object allows it.
參考範例 – https://clay-atlas.com/blog/2019/11/30/python-chinese-tutorial-function-setattr-getattr/
這邊定義了 test 這個 class 包含 a 與 b 兩個屬性並給予值.
[root@localhost ~]# python3 Python 3.6.8 (default, Mar 25 2022, 11:15:52) [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> class test(object): ... a = 123 ... b = 'today' ...
- 範例 : hasattr
>>> hasattr(test, 'a') True >>> hasattr(test, 'b') True >>> hasattr(test, 'c') False
說明:
透過 hasattr 函數來檢視屬性是否存在,有回傳 True , 無回傳 False. - 範例 : getattr
>>> getattr(test, 'a') 123 >>> getattr(test, 'b') 'today'
說明:
透過 getattr 函數來讀取屬性的值.>>> getattr(test, 'c') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'test' has no attribute 'c'
說明:
如屬性不存在則回傳錯誤.透過下面方式可以先判斷物件的屬性是否存在,若不存在就新增該屬性.
>>> getattr(test, "d", setattr(test, "d", "ddtest")) 'ddtest' >>> getattr(test, 'd') 'ddtest'
- 範例 : setattr
>>> setattr(test, 'a', 777) >>> setattr(test, 'b', 'yesterday') >>> getattr(test, 'a') 777 >>> getattr(test, 'b') 'yesterday'
說明:
透過 setattr 函數來改變屬性的值.>>> setattr(test, 'c', 'test') >>> getattr(test, 'c') 'test'
說明:
如果屬性不存在會新增該屬性並設定該屬性的值. - 範例 : delattr
>>> hasattr(test, 'a') True >>> delattr(test, 'a') >>> hasattr(test, 'a') False
說明:
透過 delattr 函數來刪除屬性.
沒有解決問題,試試搜尋本站其他內容