Mar*_*cin 17
你想要的是不可能*.您只需在全局命名空间中创建一个变量:
myglobal = "UGHWTF"
def main():
global myglobal # prevents creation of a local variable called myglobal
myglobal = "yu0 = fail it"
anotherfunc()
def anotherfunc():
print myglobal
Run Code Online (Sandbox Code Playgroud)
不要这样做.
函数的重点是它需要参数.只需在函数中添加参数即可.如果您发现需要修改许多功能,则表明您应该将它们收集到一个类中.
*详细说明为什么这是不可能的:未声明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 <module>
caketaste()
File "prog.py", line 5, in caketaste
print cake #Output is whatever taste was
NameError: global name 'cake' is not defined
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为caketaste调用时没有cake发生任何分配.它只会在setcake被叫之后发生.
你可以在这里看到错误:http://ideone.com/HBRN4y