How can I return a default value for an attribute?(如何返回属性的默认值?)
问题描述
我有一个对象 myobject
,它可能返回 None
.如果返回None
,则不会返回属性id
:
I have an object myobject
, which might return None
. If it returns None
, it won't return an attribute id
:
a = myobject.id
所以当 myobject 为 None
时,上面的语句会导致 AttributeError
:
So when myobject is None
, the stament above results in a AttributeError
:
AttributeError: 'NoneType' object has no attribute 'id'
如果 myobject
为 None,那么我希望 a
等于 None
.如何在一行语句中避免此异常,例如:
If myobject
is None, then I want a
to be equal to None
. How do I avoid this exception in one line statement, such as:
a = default(myobject.id, None)
推荐答案
你应该使用 getattr
包装器,而不是直接检索 id
的值.
a = getattr(myobject, 'id', None)
这就像说我想从对象myobject
中检索属性id
,但是如果里面没有属性id
对象 myobject
,然后返回 None
."但它确实有效.
This is like saying "I would like to retrieve the attribute id
from the object myobject
, but if there is no attribute id
inside the object myobject
, then return None
instead." But it does it efficiently.
有些对象还支持以下形式的getattr
访问:
Some objects also support the following form of getattr
access:
a = myobject.getattr('id', None)
根据 OP 要求,'deep getattr':
def deepgetattr(obj, attr):
"""Recurses through an attribute chain to get the ultimate value."""
return reduce(getattr, attr.split('.'), obj)
# usage:
print deepgetattr(universe, 'galaxy.solarsystem.planet.name')
简单解释:
Reduce 就像一个就地递归函数.在这种情况下,它的作用是从 obj
(universe)开始,然后为您尝试使用 getattr
访问的每个属性递归地深入,所以在您的问题中它会是像这样:
Reduce is like an in-place recursive function. What it does in this case is start with the obj
(universe) and then recursively get deeper for each attribute you try to access using getattr
, so in your question it would be like this:
a = getattr(getattr(myobject, 'id', None), 'number', None)
这篇关于如何返回属性的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何返回属性的默认值?


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01