为什么内部函数无法在python的外部范围中获取变量

时间:2018-08-11 12:35:16

标签: python variables scope environment-variables

def foo():
    m = 3
    def bar():
        print(m) # code 1
        m=4 # code 2
    bar()
foo()
  

UnboundLocalError:分配前引用了本地变量'm'

为什么我得到UnboundLocalError?我知道bar不能更改m的值,但是bar不能仅仅能够获取m的值吗?

当我分别尝试使用代码1/code 2时,一切都正常。

1 个答案:

答案 0 :(得分:1)

由于内部函数bar具有赋值m=4,因此对于整个函数,m被视为局部变量。但是在您调用print(m)时,尚未创建m。因此,您得到错误UnboundLocalError: local variable 'm' referenced before assignment

要解决此问题,请声明m作为全局变量。或避免在bar

中分配