未定义全局名称“p1”

2024-10-01 19:19:42 发布

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

我在函数定义中有以下函数(见下文)。在

当我运行>;>>pd=distrib(10,listAll)时,我得到了这个结果(注意行号对应于我的文件中不在下面示例中的行)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "transportOpt.py", line 78, in distrib
N = NN(0,t1)
File "transportOpt.py", line 48, in NN
print(p1,p2)
NameError: global name 'p1' is not defined

函数本身

^{pr2}$

怎么了? 我是不是用错了“全球”这个词?在


Tags: 函数inpygt定义linennfile
3条回答

必须在函数“distrib(Nm,lf):”之外定义p1和p2。全局函数用于更改原始函数之外的变量值,而不是将它们导入到sub-def

p1 = 0
p2 = 0

def distrib(Nm,lf):
    l = len(lf)
    pd = {}# the output dictionary distribution
    sumpd = 0# the total number of samples

    buf=[lf[0]]
    def NN(a,b):
        global p1,p2
        print p1,p2

也许您认为global p1使名称p1引用前面一行中用p1=0定义的变量。它没有这样做,因为前面的变量不是全局变量,它是函数distrib的局部变量。在

定义嵌套函数时,不需要global引用外部变量。但是,您不能(通过任何合理的方式)从Python2.7中的嵌套函数中赋值给外部变量。您需要使用nonlocal,而且它只在python3.0+中使用。在嵌套函数中对p1赋值的事实阻止了名称在外部函数中引用p1,而使用global也无济于事。在

你在distrib之外定义了p1吗?这可能是您的问题,因为p1和p2仍然在distib函数中使用,它们是“封闭的”,python将知道要操作哪些变量。彻底摆脱全球债务危机,它应该会奏效的。 有关范围的更多信息: Short Description of the Scoping Rules? 注意LEGB规则。本地、封闭、全局、内置

相关问题 更多 >

    热门问题