函数作为另一个函数的参数可以更新列表,但不能更新整数

时间:2016-04-24 03:55:35

标签: python

def node_count(tree):
   if is_leaf_node(tree):
      return 0
   count = 1
   def inc_count(node): #node argument not used her, but needed in call
      count += 1
  tree_traversal(tree, inc_count)
  return count

tree_traversal 将一个函数应用于树中的每个节点,并且工作正常。 这个方法给了我: UnboundLocalError:局部变量' count'在分配之前引用

但这有效:

 def node_count(tree):
    if is_leaf_node(tree):
       return 0
    l = []
    def inc_count(node): #node argument not used her, but needed in call
       l.append(1) #Add whatever
    tree_traversal(tree, inc_count)
    return len(l)

为什么呢?

最后一种方法有效,但看起来很奇怪。其他任何方式吗?

3 个答案:

答案 0 :(得分:2)

第一个是将count分配给count + 1。由于您在=的两侧使用相同的变量名称,因此Python假定您在两种情况下都在讨论相同的对象。但是,count未声明global(或Python 3中的nonlocal),因此您尝试将本地count分配给本地count + 1.问题:还没有本地count这样的东西。解决方案(Python 3中的 ):

def node_count(tree):
   if is_leaf_node(tree):
      return 0
   count = 1
   def inc_count(node): #node argument not used her, but needed in call
      nonlocal count
      count += 1
  tree_traversal(tree, inc_count)
  return count

在Python 2中似乎没有一个好的,简单的解决方案,但你至少可以在列表中使用实际数字而不是找到总和:

def node_count(tree):
   if is_leaf_node(tree):
      return 0
   count = [1]
   def inc_count(node): #node argument not used her, but needed in call
      count[0] += 1
  tree_traversal(tree, inc_count)
  return count[0]

答案 1 :(得分:0)

如果您使用的是Python3,请尝试使用nonlocal

def node_count(tree):
    if is_leaf_node(tree):
        return 0
    count = 1
    def inc_count(node): #node argument not used her, but needed in call
        nonlocal count
        count += 1
    tree_traversal(tree, inc_count)
    return count

对于Python2,您可以引用PEP 3104 - Access to Names in Outer Scopes

答案 2 :(得分:0)

在python中,允许隐式使用非局部变量,但仅用于读取。

也就是说,在您的代码中:

count = 0
def inc_count(node):
    count += 1

count的第二次使用是非本地引用,如果您不尝试修改它,则允许使用该引用。但是修改非本地符号被认为是错误的来源,因此您需要明确承认您知道它不是本地的。

在python 3中,您可以将nonlocal关键字用于此目的,或者将global关键字用于全局变量。在python 2中,只有global关键字可用。

但是,列表很有趣。您无法修改列表,但可以阅读。由于列表实际上是指向底层对象的指针,因此您可以阅读"它然后在其值上使用[]之类的运算符。这似乎解决了无修改 - 无声明规则。

如果您正在执行python 2,并且没有nonlocal语句,则可以考虑执行类似count = [0]然后count[0] += 1的操作。