【问题标题】:Variable defined in a function, needed within a function within this function - Python [duplicate]在函数中定义的变量,在此函数内的函数中需要 - Python [重复]
【发布时间】:2017-01-01 23:23:31
【问题描述】:

我需要在函数中定义一个变量,并在原始函数中的函数中使用它。例如,

def go_to_next_function():
    globvar = 0
    def add_one_to_globvar():
        global globvar  
        for i in range(10):
            globvar += 1
            print(globvar)
    add_one_to_globvar()
go_to_next_function()

现在我知道如果globvar 是在所有函数之外定义的,那么它会起作用,但我希望它在go_to_next_function() 函数中定义。有任何想法吗?谢谢。

【问题讨论】:

  • python2 还是 python3?在python3中你可以使用nonlocal
  • 在 Python 3 中

标签: python function global-variables variable-assignment


【解决方案1】:

如果您使用的是 python3.x,则可以使用 nonlocal 关键字而不是 global,您的函数应该可以工作。

如果您使用的是 python2.x,那么您会遇到一些旧技巧,例如将值放入容器中并改变 那个。这是一个丑陋的hack(这就是为什么首先添加nonlocal):

def go_to_next_function():
    closure_var = [0]
    def add_one():
        closure_var[0] += 1
        print closure_var[0]
    add_one()
go_to_next_function()

【讨论】:

  • 谢谢。我正在使用 Python 3
猜你喜欢
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 1970-01-01
相关资源
最近更新 更多