Python 范围:“UnboundLocalError:在赋值之前引用了局部变量‘c’"; [英] Python scope: "UnboundLocalError: local variable 'c' referenced before assignment"

查看:59
本文介绍了Python 范围:“UnboundLocalError:在赋值之前引用了局部变量‘c’";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决这个问题:

I am trying to figure out this:

c = 1
def f(n):
    print c + n 
def g(n):
    c = c + n

f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment

谢谢!

推荐答案

在函数内,默认情况下,分配给的变量被视为局部变量.要分配给全局变量,请使用 global 声明:

Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global statement:

def g(n):
    global c
    c = c + n

这是 Python 的古怪领域之一,我从来没有真正适应过.

This is one of the quirky areas of Python that has never really sat well with me.

这篇关于Python 范围:“UnboundLocalError:在赋值之前引用了局部变量‘c’";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆