繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM