我有一个文件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
如果尚未定义func
,我该如何修改x
?
答案 0 :(得分:3)
def func():
global x
if 'x' not in globals():
x = 0
x += 10
print(x)