1

我有一个算法来填充树状结构(类:Scan_instance_tree),但不幸的是,在每次调用期间,它都错误地添加到根节点的子节点,以及在树中进一步创建的新子节点。

作为线索,我看到了另一个线程......

递归python函数中的持久对象

...简要提到了这个问题,并建议传递的参数必须是可变的。这就是答案,在这个例子中我将如何做到这一点???

这是我当前的代码:

class Field_node(object):
    field_phenotype_id = -1
    field_name = ''
    field_parent_id = -1
    child_nodes = []          


class Scan_instance_tree(object):
    root_node = None  

    def __init__(self, a_db):
        self.root_node = Field_node()
        scan_field_values = self.create_scan_field_values(a_db)   # This just creates a temporary user-friendly version of a database table    
        self.build_tree(scan_field_values)  

    def build_tree(self, a_scan_field_values):
        self.root_node.field_name = 'ROOT'      
        self.add_child_nodes(a_scan_field_values, self.root_node)


    def add_child_nodes(self, a_scan_field_values, a_parent_node):
        i = 0
        while i < len(a_scan_field_values):
            if a_scan_field_values[i]['field_parent_dependancy'] == a_parent_node.field_phenotype_id:
                #highest_level_children.append(a_scan_field_values.pop(a_scan_field_values.index(scan_field))) 
                child_node = Field_node()
                child_node.field_phenotype_id = a_scan_field_values[i]['field_phenotype_id']
                child_node.field_name = a_scan_field_values[i]['field_name']
                child_node.field_parent_dependancy = a_scan_field_values[i]['field_parent_dependancy']

                a_parent_node.child_nodes.append(child_node)
                a_scan_field_values.remove(a_scan_field_values[i])

                # RECURSION: get the child nodes
                self.add_child_nodes(a_scan_field_values, child_node)
            else: 
                i = i+1

如果我删除对 self.add_child_nodes(...) 的递归调用,则根的子节点被正确添加,即它们仅包含那些 field_parent_dependancy = -1 如果我允许递归调用,则根的子节点包含所有节点,无论 field_parent_dependancy 值如何。

此致

4

1 回答 1

2

When you define your Field_node class, the line

    child_nodes = []

is actually instantiating a single list as a class attribute, rather than an instance attribute, that will be shared by all instances of the class.

What you should do instead is create instance attributes in __init__, e.g.:

class Field_node(object):
    def __init__(self):
        self.field_phenotype_id = -1
        self.field_name = ''
        self.field_parent_id = -1
        self.child_nodes = []
于 2012-12-20T13:56:15.367 回答