如何检查对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
如何在使用属性属性之前确定它是否具有属性属性?
如何检查对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
如何在使用属性属性之前确定它是否具有属性属性?
当前回答
这非常简单,只需使用dir(object)这将返回对象的每个可用函数和属性的列表。
其他回答
您可以使用hasattr内置方法检查对象是否包含属性。
对于一个实例,如果您的对象是,并且您想检查属性
>>> class a:
... stuff = "something"
...
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False
方法签名本身是hasattr(object,name)->bool,这意味着如果对象具有传递给hasattr中的第二个参数的属性,则根据对象中name属性的存在,它会给出布尔值True或False。
对于字典以外的对象:
if hasattr(a, 'property'):
a.property
对于字典,hasattr()将不起作用。
许多人都在告诉字典使用has_key(),但它已经贬值了。因此,对于字典,必须使用has_attr()
if a.has_attr('property'):
a['property']
或者您也可以使用
if 'property' in a:
您可以使用hasattr()或catch AttributeError,但如果您真的只希望属性的值具有默认值(如果不存在),最好的选择就是使用getattr(
getattr(a, 'property', '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的意图半匹配,您可以在任何地方重用它的定义,并且它总是匹配的。缺点是它在布尔值中是“真实的”,在日志和堆栈跟踪中看起来很奇怪(但当你知道它只出现在这个上下文中时,你很快就会忘记它)。
这非常简单,只需使用dir(object)这将返回对象的每个可用函数和属性的列表。