查找嵌套 Python 对象的自索引

find self index for nested Python object

class Node:
    def __init__(self,parent = None):
        self.parent = parent
        self.children = []
    def AddNode(self):
        self.children.append(Node(self))
    def getIndex(self):
        return self.parent.children.index(self)

a = Node()
b = a.AddNode()
print b.getIndex()

在像上面这样的对象树中,子项在父项的子项中找到其索引的最佳方法是什么?我正在使用 self.parent.children.index(self),但这似乎有些扭曲。有没有更好的方法?

一点:这不太行得通,因为 AddNode 没有 return 任何东西。 除此之外,你所做的一切都很好。只要您正在对索引进行 on-demand(惰性)检索,这就是一种直接的方法。如果你想要更直接的东西,我建议你在 child 链接时存储索引 AddNode.

class Node:

    def __init__(self,parent = None):
        self.parent = parent
        self.children = []
        self.child_index = None

    def AddNode(self):
        new_child = Node(self)
        self.children.append(new_child)
        new_child.child_index = self.children.index(new_child)
        return new_child

    def getIndex(self):
        return self.child_index

a = Node()
b = a.AddNode()
c = a.AddNode()
d = a.AddNode()

print d.getIndex()
print c.getIndex()
print b.getIndex()

输出(booooorrriiiinnngg):

2
1
0