简体   繁体   English

从父级的 function scope 覆盖变量

[英]overwrite variable from parent's function scope

I'm trying to write a recursive function.我正在尝试编写递归 function。 When i write code like this one.当我写这样的代码时。 It works fine.它工作正常。

def older_func():
    variable = 1
    def func():
       print(variable)

       return func

    return func
older_func()(5)

But if I try to reassign my variable after printing i get an error但是如果我在打印后尝试重新分配我的变量,我会得到一个错误

def older_func():
    variable = 1
    def func(n):
       print(variable)
       variable = n
       return func

    return func
older_func()(5)

local variable referenced before assignment.赋值前引用的局部变量。 on printing step.在打印步骤上。 Please help me understand behavior and way to overcome this.请帮助我理解行为和克服这个问题的方法。

UnboundLocalError: local variable 'variable' referenced before assignment UnboundLocalError:分配前引用的局部变量“变量”

There is no error code just returns a function object because you don't call the actual function you Just return it return func没有错误代码只是返回一个 function object 因为你没有调用实际的 function 你只是返回它return func

but when you call it return func(n) it will raise UnboundLocalError: local variable 'variable' referenced before assignment so you need to use nonlocal Keyword但是当你调用它时return func(n)它会引发 UnboundLocalError: local variable 'variable' referenced before assignment 所以你需要使用nonlocal关键字

def older_func():
   variable = 1

   def func(n):
      nonlocal variable
      print(variable)
      variable = n
      return func

   return func(5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM