你想要什么是不可能的*。你可以在全局命名空间中创建一个变量:
myglobal = "UGHWTF"
def main():
global myglobal # prevents creation of a local variable called myglobal
myglobal = "yu0 = fail it"
anotherfunc()
def anotherfunc():
print myglobal
不要这样做。
函数的全部要点是它需要参数。只需将参数添加到您的功能。如果你发现你需要修改很多功能,这表明你应该将它们收集到一个班级中。
*为了详细说明为什么这是不可能的:python中的变量没有声明 - 它们是在执行赋值语句时创建的。这意味着下面的代码(从张贴astronautlevel代码派生)将打破:
def setcake(taste):
global cake
cake = taste
def caketaste():
print cake #Output is whatever taste was
caketaste()
Traceback (most recent call last):
File "prog.py", line 7, in
caketaste()
File "prog.py", line 5, in caketaste
print cake #Output is whatever taste was
NameError: global name 'cake' is not defined
这是因为当caketaste被调用时,没有分配给cake发生。它只会在调用setcake后才会发生。