Python参数范围 - 相同的对象?

时间:2014-03-03 01:22:55

标签: python python-2.7 python-3.x scope arguments

我正在编写一个简单的DFS算法,但是当我运行该函数时,我传入的参数似乎会继续进行下一次调用。我对Python的作用方式感到有些自在,但我从未真正考虑过范围如何适用于参数。有人可以解释这个范围问题是如何发生的吗?

我能想到的唯一原因是每次运行函数时都不会重新创建我给出路径的默认值...?

图表对象:

graph = {
        1: [2,8,12],
        2: [3,7],
        3: [4,5,6],
        8: [9],
        9: [10,11],
        12: [13],
        13: [14]
      }

DFS算法:

def dfs_dict(graph, curr, val, path=[]):
  path.append(curr)
  print "Path: " + str(path)
  if curr == val:
    return path
  else:
    if curr in graph: # not a disconnected node/leaf
      for child in graph[curr]:
        if child not in path:
          tmp = dfs_dict(graph, child, val, path)
          if tmp:
            return tmp

我如何运行DFS:

if __name__ == '__main__':
    print dfs_dict(graph, 1, 13)
    print dfs_dict(graph, 1, 7)

输出:

Path: [1]
Path: [1, 2]
Path: [1, 2, 3]
Path: [1, 2, 3, 4]
Path: [1, 2, 3, 4, 5]
Path: [1, 2, 3, 4, 5, 6]
Path: [1, 2, 3, 4, 5, 6, 7]
Path: [1, 2, 3, 4, 5, 6, 7, 8]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Path: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1]
None

1 个答案:

答案 0 :(得分:2)

问题是path的默认值:def dfs_dict(graph, curr, val, path=[]):

列表是一次,当首次读取代码时,然后反复使用相同的实例,如下例所示:

>>> def foo(bar=[]):
...  bar.append(1)
...  print(bar)
... 
>>> foo()
[1]
>>> foo()
[1, 1]
>>> foo()
[1, 1, 1]
>>> bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined

你应该开始这样的功能:

def dfs_dict(graph, curr, val, path=None):
    if path is None:
        path = []

编辑:此外,由于列表是可变的,您可能应该在dfs_dict的开头复制,以便在附加项目时不修改使用“父”堆栈帧的那个。