訪問我的博客 http://blog.colinspace.com
摘要
Python 對應屬性和方法的判斷 hasattr/getattr/setattr
hasattr
判斷一個對象里面是否有name屬性或者方法,返回值為Boolean值, 有name 返回true,反之false
其等同于getattr(object, name)
hasattr(object, name)
getattr
類似于hasattr(object, name)
,但是getattr當name不存在于object的時候返回default值。否則返回實際的值
getattr(object, name[, default])
setattr
給對象的屬性復制,如果屬性不存在,則先創建再賦值
setattr(object, name, value)
examples
root@pts/1 $ python
Python 3.5.3 (default, Jul 20 2017, 16:49:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help(getattr)
>>>
## 定義測試類
>>> class TestAttr():
... name = 'James'
...
... def sayHello(self):
... return 'Hello James'
...
>>> ta = TestAttr()
## ta為object對象類型
>>> ta
<__main__.TestAttr object at 0x7f52d55df5f8>
## hasattr 測試, name屬性必須加引號
>>> hasattr(ta, name)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
>>> hasattr(ta, "name")
True
>>> hasattr(ta, "sayHello")
True
## hasattr 不能像getattr 那樣調用函數
>>> hasattr(ta, "sayHello")()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not callable
>>>
## setattr測試,當不存在屬性的時候可以創建屬性
>>> hasattr(ta, "age")
False
>>> setattr(ta, "age", 28)
>>> hasattr(ta, "age")
True
>>>
## getattr 測試
>>> getattr(ta, "name")
'James'
## 是函數的時候,可以調用函數
>>> getattr(ta, "sayHello")
<bound method TestAttr.sayHello of <__main__.TestAttr object at 0x7f52d55df5f8>>
>>> getattr(ta, "sayHello")()
'Hello James'
>>> getattr(ta, "age")
28
## 不存在的時候得到默認值
>>> getattr(ta, "age2", 18)
18
>>>
Note & Refer to:
從上面的例子中我們看到
- name 參數必須是加引號,不然報錯
- name 為函數的時候,調用
getattr(object, name)()
相當于 object.name 調用該name函數
例子用法參考官網地址: