[英]How can I define a global variable in a function?
我有一个文件f.py
:
def func():
if 'x' not in globals():
setattr(f, 'x', 0)
global x
x += 10
print x
我正在一个互动环节:
>>> import f
>>> f.func()
Traceback (most recent call last):
[...]
NameError: global name 'x' is not defined
如果尚未定义x
我该如何修改func
来定义它?
def func():
global x
if 'x' not in globals():
x = 0
x += 10
print(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.