您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何链接可能在Python中返回None的属性查找?

如何链接可能在Python中返回None的属性查找?

您可能可以使用reduce功能

>>> class Foo(object): pass
... 
>>> a = Foo()
>>> a.foo = Foo()
>>> a.foo.bar = Foo()
>>> a.foo.bar.baz = Foo()
>>> a.foo.bar.baz.qux = Foo()
>>> 
>>> reduce(lambda x,y:getattr(x,y,''),['foo','bar','baz','qux'],a)
<__main__.Foo object at 0xec2f0>
>>> reduce(lambda x,y:getattr(x,y,''),['foo','bar','baz','qux','quince'],a)
''

python3.x中,我认为它reduce已移至functools:(

我想您也可以使用更简单的功能来做到这一点:

def attr_getter(item,attributes)
    for a in attributes:
        try:
            item = getattr(item,a)
        except AttributeError:
            return None #or whatever on error
    return item

最后,我想 最好的 方法是:

try:
   title = foo.bar.baz.qux
except AttributeError:
   title = None
python 2022/1/1 18:48:30 有353人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶