相关疑难解决方法(0)

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

有没有办法在Python中确定对象是否具有某些属性?例如:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

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

python attributes

1491
推荐指数
13
解决办法
78万
查看次数

hasattr()vs try-except块来处理不存在的属性

if hasattr(obj, 'attribute'):
    # do somthing
Run Code Online (Sandbox Code Playgroud)

VS

try:
    # access obj.attribute
except AttributeError, e:
    # deal with AttributeError
Run Code Online (Sandbox Code Playgroud)

哪个应该是首选,为什么?

python attributes exception-handling exception hasattr

80
推荐指数
7
解决办法
3万
查看次数