一种类似于get()的用于检查Python属性的方法 [英] A get() like method for checking for Python attributes
问题描述
如果我有字典dict
,并且想检查dict['key']
,则可以在try
块中完成(可笑!),也可以使用get()
方法,默认情况下为False
值.
If I had a dictionary dict
and I wanted to check for dict['key']
I could either do so in a try
block (bleh!) or use the get()
method, with False
as a default value.
我想对object.attribute
做同样的事情.也就是说,如果尚未设置False
,我已经有对象要返回它,但是这样会给我类似
I'd like to do the same thing for object.attribute
. That is, I already have object to return False
if it hasn't been set, but then that gives me errors like
AttributeError:布尔"对象没有属性属性"
AttributeError: 'bool' object has no attribute 'attribute'
推荐答案
与hasattr
相比,与dict.get(key, default)
更为直接的类比是getattr
.
A more direct analogue to dict.get(key, default)
than hasattr
is getattr
.
val = getattr(obj, 'attr_to_check', default_value)
(其中default_value
是可选的,如果找不到该属性,则会引发异常).
(Where default_value
is optional, raising an exception on no attribute if not found.)
例如,您将通过False
.
这篇关于一种类似于get()的用于检查Python属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!