我有一棵对象树,我需要检查特定对象是否包含对象的特定分支。例如:
def specificNodeHasTitle(specificNode):
# something like this
return specificNode.parent.parent.parent.header.title != None
如果缺少所需的属性,是否有一种优雅的方法来执行此操作而不会引发异常?
只要您在项目路径中不需要数组的索引,此方法就起作用。
def getIn(d, arraypath, default=None):
if not d:
return d
if not arraypath:
return d
else:
return getIn(d.get(arraypath[0]), arraypath[1:], default) \
if d.get(arraypath[0]) else default
getIn(specificNode,["parent", "parent", "parent", "header", "title"]) is not None
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句