你想要什么是不可能的*。你可以在全局命名空間中創建一個變量:
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后才會發生。