0

我有以下用于 Category/Leaf 实现的类:

class CategoryMapper():
    @staticmethod
    def get_tree():
        categories = []
        tree_categories = Category.objects.filter(parent_id__isnull = True) 
        for tree_category in tree_categories:
            leaf_categories = CategoryMapper.get_leafs(tree_category)
            categories += leaf_categories

        return categories

    @staticmethod
    def get_leafs(tree_category, leaf_categories = [], depth = 0):
        if depth > 0:
            child_categories = Category.objects.filter(parent_id__exact = tree_category.id)
            if len(child_categories):
                depth += 1
                for sub_category in child_categories:
                    sub_category_name = ((depth - 1) * '-') + sub_category.category
                    leaf_categories.append([sub_category.id, sub_category_name])

                    return CategoryMapper.get_leafs(sub_category, leaf_categories, depth)
            else:
                return leaf_categories
        else:
            leaf_categories.append([tree_category.id, tree_category.category])
            depth += 1

            return CategoryMapper.get_leafs(tree_category, leaf_categories, depth)

我有以下日期:ID|类别|父母 ID 1|测试 1|无 2|测试 1 孩子|1 3|测试 2|无

当我运行它(CategoryMapper.get_tree())时,我得到:

[[1, u'Test 1'], [2, u'-Test 1 Child'], [1, u'Test 1'], [2, u'-Test 1 Child'], [3, u'Test 2']]

当我再次运行它时,我得到:

[[1, u'Test 1'], [2, u'-Test 1 Child'], [3, u'Test 2'], [1, u'Test 1'], [2, u'-Test 1 Child'], [1, u'Test 1'], [2, u'-Test 1 Child'], [3, u'Test 2'], [1, u'Test 1'], [2, u'-Test 1 Child'], [3, u'Test 2']]

它就像 get_tree() 中的类别变量一样,每次运行 for 循环时都会在遍历 tree_categories 时保持其状态。我究竟做错了什么?为什么它保持这样的状态?

4

1 回答 1

2

啊,你需要避免使用可变对象作为函数的默认参数,比如 []。相反,只需get_leafs像这样定义:

def get_leafs(tree_category, leaf_categories = None, depth = 0):
    if leaf_categories is None:
        leaf_categories = []
    …
于 2013-07-14T03:09:56.353 回答