我在函数定义中有以下函数(见下文)。在
当我运行>;>>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}$怎么了? 我是不是用错了“全球”这个词?在
必须在函数“distrib(Nm,lf):”之外定义p1和p2。全局函数用于更改原始函数之外的变量值,而不是将它们导入到sub-def
也许您认为
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规则。本地、封闭、全局、内置
相关问题 更多 >
编程相关推荐