Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

python - 如何知道对象在Python中是否具有属性(How to know if an object has an attribute in Python)

Is there a way in Python to determine if an object has some attribute?

(有没有办法在Python中确定对象是否具有某些属性?)

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'

How can you tell if a has the attribute property before using it?

(在使用之前如何判断a是否具有属性property ?)

  ask by Lucas Gabriel Sánchez translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try hasattr() :

(尝试hasattr() :)

if hasattr(a, 'property'):
    a.property

EDIT: See zweiterlinde's answer below, who offers good advice about asking forgiveness!

(编辑:请参阅下面的zweiterlinde的答案 ,谁提供了关于请求宽恕的好建议!)

A very pythonic approach!

(一种非常pythonic的方法!)

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.

(python中的一般做法是,如果属性可能在大多数时间都存在,只需调用它并让异常传播,或者使用try / except块捕获它。)

This will likely be faster than hasattr .

(这可能会比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.

(如果该属性很可能在大多数时间不存在,或者您不确定,使用hasattr可能会比重复进入异常块更快。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...