本文目錄一覽:
- 1、Python3.x中hasattr用法
- 2、怎麼判斷 Python 對象是否包含某個屬性
- 3、python中hasattr是什麼意思
- 4、怎麼判斷 Python 對象是否包含某個屬性
- 5、Python 中的hasattr 只能作用於類對象嗎?
Python3.x中hasattr用法
hasattr(object, name):
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises anAttributeError or not.)
for example:
“`python
s = “hello world”
print (hasattr(s, “__iter__”)) #hasattr(s, “__iter__”)##意思就是看看s對象有沒有__iter__屬性。
“`
怎麼判斷 Python 對象是否包含某個屬性
頂級函數hasattr可以查看對象是否包含某某屬性,這裡的屬性包括數據屬性和方法。getattr可以獲取屬性。
如下舉例說明。
a=[1,2,3]
print(‘列表有count屬性:%s’%hasattr(a,’count’))
print(‘列表有append屬性:%s’%hasattr(a,’append’))
print(‘列表有shift屬性:%s’%hasattr(a,’shift’))
print(‘列表的count屬性是方法:%s’%hasattr(getattr(a,’count’),’__call__’))
print(‘列表的append屬性是方法:%s’%hasattr(getattr(a,’append’),’__call__’))
class myclass():
def __init__(self):
self.valattr=3
def method(self):
pass
mc=myclass()
print(‘myclass有valattr屬性:%s’%hasattr(mc,’valattr’))
print(‘myclass有method屬性:%s’%hasattr(mc,’method’))
print(‘myclass的valattr屬性是方法:%s’%hasattr(getattr(mc,’valattr’),’__call__’))
print(‘myclass的method屬性是方法:%s’%hasattr(getattr(mc,’method’),’__call__’))
python中hasattr是什麼意思
hasattr(object, name)
作用:判斷對象object是否包含名為name的特性(hasattr是通過調用getattr(ojbect, name)是否拋出異常來實現的)。
示例:
hasattr(list, ‘append’)
True
hasattr(list, ‘add’)
False
怎麼判斷 Python 對象是否包含某個屬性
頂級函數hasattr可以查看對象是否包含某某屬性,這裡的屬性包括數據屬性和方法。getattr可以獲取屬性。
如下舉例說明。
a=[1,2,3]
print(‘列表有count屬性:%s’%hasattr(a,’count’))
print(‘列表有append屬性:%s’%hasattr(a,’append’))
print(‘列表有shift屬性:%s’%hasattr(a,’shift’))
print(‘列表的count屬性是方法:%s’%hasattr(getattr(a,’count’),’__call__’))
print(‘列表的append屬性是方法:%s’%hasattr(getattr(a,’append’),’__call__’))
class myclass():
def __init__(self):
self.valattr=3
def method(self):
pass
mc=myclass()
print(‘myclass有valattr屬性:%s’%hasattr(mc,’valattr’))
print(‘myclass有method屬性:%s’%hasattr(mc,’method’))
print(‘myclass的valattr屬性是方法:%s’%hasattr(getattr(mc,’valattr’),’__call__’))
print(‘myclass的method屬性是方法:%s’%hasattr(getattr(mc,’method’),’__call__’))
Python 中的hasattr 只能作用於類對象嗎?
hasattr同樣適用於對象中的方法,因為方法也是屬性。
如果對象obj中有get方法,hasattr(obj,’get’)將返回True。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/298091.html