检查对象路径在对象树中是否存在

0 投票
3 回答
760 浏览
提问于 2025-04-18 01:21

我有一棵对象树,我需要检查某个特定的对象是否包含某个特定的对象分支。比如说:

def specificNodeHasTitle(specificNode):
    # something like this
    return specificNode.parent.parent.parent.header.title != None

有没有一种优雅的方法来做到这一点,而不需要在缺少所需属性时抛出异常呢?

3 个回答

0

针对你的具体情况,unutbu 提供的解决方案是最好的,也是最符合 Python 风格的。不过,我还是想展示一下 Python 的强大功能,以及它的getattr 方法:

#!/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 真棒 :)

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

只要你在找到某个项目的过程中不需要用到数组的索引,这样做就没问题。

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

撰写回答