用i中的另一个方法更改方法中的变量

2024-03-29 11:42:41 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码引发一个UnboundLocalError

def foo():
    i = 0
    def incr():
        i += 1
    incr()
    print(i)

foo()

有没有办法做到这一点?在


Tags: 代码foodefprint办法incrunboundlocalerror
3条回答

9.2. Python Scopes and Namespaces

if no global statement is in effect – assignments to names always go into the innermost scope.

同时:

The global statement can be used to indicate that particular variables live in the global scope and should be rebound there; the nonlocalstatement indicates that particular variables live in an enclosing scope and should be rebound there.

您有许多解决方案:

  • i作为参数✓传递(我将使用这个参数)
  • 使用nonlocal关键字

请注意,在Python2.x中,您可以访问非局部变量,但您不能更改它们。在

您可以使用i作为如下参数:

def foo():
    i = 0
    def incr(i):
        return i + 1
    i = incr(i)
    print(i)

foo()

使用nonlocal语句

def foo():
    i = 0
    def incr():
        nonlocal i
        i += 1
    incr()
    print(i)

foo()

有关python3.x中添加的这个新语句的更多信息,请转到https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement

相关问题 更多 >