7 回答

TA貢獻1841條經(jīng)驗 獲得超3個贊
如果它是一本字典,你可以使用get(keyname, value)
{'foo': {'bar': 'baz'}}.get('foo', {}).get('bar')

TA貢獻1883條經(jīng)驗 獲得超3個贊
最Pythonic的方式是:
try:
# do something
...
except (NameError, AttributeError) as e:
# do something else
...

TA貢獻1828條經(jīng)驗 獲得超13個贊
你可以使用格洛姆。
from glom import glom
target = {'a': {'b': {'c': 'd'}}}
glom(target, 'a.b.c', default=None) # returns 'd'
https://github.com/mahmoud/glom

TA貢獻1873條經(jīng)驗 獲得超9個贊
結(jié)合我在這里看到的一些東西。
from functools import reduce
def optional_chain(obj, keys):
try:
return reduce(getattr, keys.split('.'), obj)
except AttributeError:
return None
optional_chain(foo, 'bar.baz')
或者擴展,getattr這樣你也可以使用它作為替代品getattr
from functools import reduce
def rgetattr(obj, attr, *args):
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return reduce(_getattr, attr.split('.'), obj)
如果路徑不存在,它仍然可以引發(fā)一個,并且您可以指定自己的默認值而不是“無” rgetattr。AttributeError

TA貢獻1818條經(jīng)驗 獲得超11個贊
將其他一些答案組合到一個函數(shù)中可以為我們提供易于閱讀的內(nèi)容以及可以與對象和字典一起使用的內(nèi)容。
def optional_chain(root, *keys):
result = root
for k in keys:
if isinstance(result, dict):
result = result.get(k, None)
else:
result = getattr(result, k, None)
if result is None:
break
return result
使用此函數(shù),您只需在第一個參數(shù)之后添加鍵/屬性。
obj = {'a': {'b': {'c': {'d': 1}}}}
print(optional_chain(obj, 'a', 'b'), optional_chain(obj, 'a', 'z'))
給我們:
{'c': {'d': 1}} None

TA貢獻1828條經(jīng)驗 獲得超3個贊
類可以覆蓋__getattr__以返回缺失屬性的默認值:
class Example:
def __getattr__(self, attr): # only called when missing
return None
測試它:
>>> ex = Example()
>>> ex.attr = 1
>>> ex.attr
1
>>> ex.missing # evaluates to `None
>>>
但是,這不允許鏈接:
>>> ex.missing.missing
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'missing'
它也不會處理調(diào)用不存在的方法的嘗試:
>>> ex.impossible()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
為了解決這個問題,我們可以創(chuàng)建一個代理對象:
class GetAnything:
def __getattr__(self, attr):
return self
def __call__(self, *args, **kwargs): # also allow calls to work
return self
def __repr__(self):
return '<Missing value>'
# Reassign the name to avoid making more instances
GetAnything = GetAnything()
并返回它而不是None:
class Example:
def __getattr__(self, attr): # only called when missing
return GetAnything
現(xiàn)在它根據(jù)需要鏈接:
>>> Example().missing_attribute.missing_method().whatever
<Missing value>
添加回答
舉報