默认参数未在类方法中重新初始化

时间:2020-09-18 15:29:27

标签: python

我有这种深度优先的树遍历方法:

   def dfs(self, node, visited=[], level=0):
        print( f"len(dfs) visited is {len(visited)} level is {level}.")
        if not node:
            return None

        if node not in visited:
            print(f"{level} {node.value}")
            visited.append(node)
            for child in [node.left, node.right]:
                self.dfs(node=child, visited=visited, level=level+1)

我这样称呼此方法:

>>> from binary_tree import Tree
>>> import random
>>> t = Tree()
>>> for i in range(10):
...     t.insert(random.randint(-10,10))
...
>>> t.dfs(t.root)
len(dfs) visited is 0 level is 0.
0 -1
... expected output ...
len(dfs) visited is 10 level is 4.

但是当我像这样重复通话时...

>>> t.dfs(t.root)

我刚得到以下输出:

len(dfs) visited is 10 level is 0.

好像visited未设置为[]visited是否应重新初始化为[]

0 个答案:

没有答案