查找嵌套Python对象的自索引

2024-09-28 21:03:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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),但这似乎有点扭曲。有更好的方法吗?在


Tags: 对象方法selfnonenodeindexreturninit
1条回答
网友
1楼 · 发布于 2024-09-28 21:03:58

一点:这不太管用,因为AddNode不返回任何内容。 除此之外,你所做的一切都很好。只要您在按需(惰性)检索索引,这是一种直接的方法。如果您想要更直接的东西,我建议您在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()

输出(booooorrriningg):

^{pr2}$

相关问题 更多 >