一个类似 get()的方法,用于检查 Python 属性

如果我有一个字典 dict,我想检查的 dict['key'],我可以这样做,在一个 try块(呸!)或者使用 get()方法,以 False作为默认值。

我想为 object.attribute做同样的事情。也就是说,如果还没有设置对象,我已经有返回 False的对象,但是这会给我一些错误,比如

AttributeError: ‘ bool’对象没有属性‘ Attribute’

48496 次浏览

Do you mean hasattr() perhaps?

hasattr(object, "attribute name") #Returns True or False

Python.org doc - Built in functions - hasattr()

You can also do this, which is a bit more cluttered and doesn't work for methods.

"attribute" in obj.__dict__

For checking if a key is in a dictionary you can use in: 'key' in dictionary.

For checking for attributes in object use the hasattr() function: hasattr(obj, 'attribute')

A more direct analogue to dict.get(key, default) than hasattr is getattr.

val = getattr(obj, 'attr_to_check', default_value)

(Where default_value is optional, raising an exception on no attribute if not found.)

For your example, you would pass False.