如何在函数中定义全局变量?

时间:2012-07-08 18:20:51

标签: python python-2.7

我有一个文件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

1 个答案:

答案 0 :(得分:3)

def func():
    global x

    if 'x' not in globals():
        x = 0

    x += 10

    print(x)