一种类似于get()的用于检查Python属性的方法 [英] A get() like method for checking for Python attributes

查看:84
本文介绍了一种类似于get()的用于检查Python属性的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有字典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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆