如何检查对象是否具有某些属性?例如:

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

如何在使用属性属性之前确定它是否具有属性属性?


当前回答

我想你要找的是哈萨特。然而,如果您想检测python财产,我建议您这样做-

try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

这里的缺点是财产__get__代码中的属性错误也会被捕获。

否则,请执行-

if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass

文件:http://docs.python.org/library/functions.html警告:我推荐的原因是hasattr无法检测财产。链接:http://mail.python.org/pipermail/python-dev/2005-December/058498.html

其他回答

希望您希望使用hasattr(),但尽量避免使用hasattr(),请选择getattr(。getattr()比hasttr()快

使用hasattr():

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

同样,我在这里使用getattr获取属性,如果没有属性,则返回none

   property = getattr(a,"property",None)
    if property:
        print property

根据pydoc,hasattr(obj,prop)只是调用getattr(obj,prop)并捕获异常。因此,用try语句包装属性访问并捕获AttributeError与预先使用hasattr()一样有效。

a = SomeClass()
try:
    return a.fake_prop
except AttributeError:
    return default_value

另一种可能的选择,但这取决于您之前的意思:

undefined = object()

class Widget:

    def __init__(self):
        self.bar = 1

    def zoom(self):
        print("zoom!")

a = Widget()

bar = getattr(a, "bar", undefined)
if bar is not undefined:
    print("bar:%s" % (bar))

foo = getattr(a, "foo", undefined)
if foo is not undefined:
    print("foo:%s" % (foo))

zoom = getattr(a, "zoom", undefined)
if zoom is not undefined:
    zoom()

输出:

bar:1
zoom!

这甚至允许您检查无值属性。

但是要非常小心,不要意外地实例化和比较未定义的多个位置,因为在这种情况下is永远不会工作。

更新:

由于我在上面的段落中警告过,有多个从未匹配的未定义,我最近稍微修改了这个模式:

undefined=未实现

NotImplemented(不要与NotImplementedError混淆)是一个内置的:它与JS undefined的意图半匹配,您可以在任何地方重用它的定义,并且它总是匹配的。缺点是它在布尔值中是“真实的”,在日志和堆栈跟踪中看起来很奇怪(但当你知道它只出现在这个上下文中时,你很快就会忘记它)。

我建议避免这样做:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

用户@jpalecek提到了这一点:如果doStuff()内部发生AttributeError,则表示您迷路了。

也许这种方法更好:

try:
    val = a.property
except AttributeError:
    otherStuff()
else:
    doStuff(val)

这非常简单,只需使用dir(object)这将返回对象的每个可用函数和属性的列表。