如何知道一个对象在Python中的一个属性 [英] How to know if an object has an attribute in Python
问题描述
有没有在Python的方式来确定对象是否具有一定的属性?例如:
Is there a way in Python to determine if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
您如何判断是否 A
具有属性属性
在使用它之前?
How can you tell if a
has the attribute property
before using it?
推荐答案
尝试hasattr():
Try hasattr():
if hasattr(a, 'property'):
a.property
编辑:请参见下面zweiterlinde的回答,谁提供了有关请求原谅很好的建议!一个非常Python的方法!
See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!
在蟒蛇一般的做法是,如果物业很可能是大部分时间在那里,简单地用一个try /调用它,要么让异常传播,或陷阱它除了块。这可能会比 hasattr
更快。如果该属性很可能不是大部分时间里面,或者你不知道,使用 hasattr
可能比反复落入异常块更快。
The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr
. If the property is likely to not be there most of the time, or you're not sure, using hasattr
will probably be faster than repeatedly falling into an exception block.
这篇关于如何知道一个对象在Python中的一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!