如果我有一个字典 dict,我想检查的 dict['key'],我可以这样做,在一个 try块(呸!)或者使用 get()方法,以 False作为默认值。
dict
dict['key']
try
get()
False
我想为 object.attribute做同样的事情。也就是说,如果还没有设置对象,我已经有返回 False的对象,但是这会给我一些错误,比如
object.attribute
AttributeError: ‘ bool’对象没有属性‘ Attribute’
Do you mean hasattr() perhaps?
hasattr()
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.
in
'key' in dictionary
For checking for attributes in object use the hasattr() function: hasattr(obj, 'attribute')
hasattr(obj, 'attribute')
A more direct analogue to dict.get(key, default) than hasattr is getattr.
dict.get(key, default)
hasattr
getattr
val = getattr(obj, 'attr_to_check', default_value)
(Where default_value is optional, raising an exception on no attribute if not found.)
default_value
For your example, you would pass False.