我有一个对象树,我需要检查特定对象是否包含特定的对象分支。例如:
def specificNodeHasTitle(specificNode):
# something like this
return specificNode.parent.parent.parent.header.title != None
如果缺少必要的属性,是否有一种优雅的方法可以在不抛出异常的情况下执行此操作?
答案 0 :(得分:1)
使用try..except
:
def specificNodeHasTitle(specificNode):
try:
return specificNode.parent.parent.parent.header.title is not None
except AttributeError:
# handle exception, for example
return False
顺便提一下,提出例外并没有错。这是Python编程的正常部分。使用try..except
是处理它们的方法。
答案 1 :(得分:1)
只要您不需要在项目路径中使用数组索引,就可以正常工作。
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
答案 2 :(得分:0)
对于您的具体情况,solution提供的unutbu是最好的,也是最蟒蛇的,但我无法帮助尝试展示python的强大功能及其{{3}方法:
#!/usr/bin/env python
# https://stackoverflow.com/questions/22864932/python-check-if-object-path-exists-in-tree-of-objects
class A(object):
pass
class Header(object):
def __init__(self):
self.title = "Hello"
specificNode=A()
specificNode.parent = A()
specificNode.parent.parent = A()
specificNode.parent.parent.parent = A()
specificNode.parent.parent.parent.header = Header()
hierarchy1="parent.parent.parent.header.title"
hierarchy2="parent.parent.parent.parent.header.title"
tmp = specificNode
for attr in hierarchy1.split('.'):
try:
tmp = getattr(tmp, attr)
except AttributeError:
print "Ouch... nopes"
break
else:
print "Yeeeps. %s" % tmp
tmp = specificNode
for attr in hierarchy2.split('.'):
try:
tmp = getattr(tmp, attr)
except AttributeError:
print "Ouch... nopes"
break
else:
print "Yeeeps. %s" % tmp
输出:
Yeeeps. Hello
Ouch... nopes
Python :)