如何知道对象在Python中是否具有属性

如何知道对象在Python中是否具有属性

Python中是否有确定对象是否具有某种属性的方法?例如:

>>> a = SomeClass()>>> a.someProperty = value>>> a.propertyTraceback (most recent call last):
  File "<stdin>", line 1, in <module>AttributeError: SomeClass instance has no attribute 'property'

你怎么知道a有属性property在使用之前?


呼如林
浏览 287回答 3
3回答

手掌心

试一试hasattr():if&nbsp;hasattr(a,&nbsp;'property'): &nbsp;&nbsp;&nbsp;&nbsp;a.property见Zweiterlinde的答案下面,他提供了关于请求宽恕的好建议!一种非常仿生的方法!python中的一般做法是,如果属性可能大部分时间都在那里,那么只需调用它,让异常传播,或者使用TRY/EXT块来捕获它。这可能比hasattr..如果属性可能大部分时间不在那里,或者您不确定,则使用hasattr可能比反复陷入异常块更快。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python