問題描述
我有一個對象 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)
這篇關于如何返回屬性的默認值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!