19

我想在 main 中定义一个全局变量,即我从 main 函数调用的任何函数都可以使用的变量。

那可能吗?这样做的好方法是什么?

谢谢!

4

3 回答 3

20

你想要的是不可能的*。您可以在全局命名空间中创建一个变量:

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 <module>
    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被调用后发生。

你可以在这里看到错误:http: //ideone.com/HBRN4y

于 2013-05-11T22:44:21.673 回答
11

方法中创建的变量(例如,main)根据定义是局部的。但是,您可以在方法之外创建一个全局变量,并从任何其他方法访问和更改其值。

要更改其值,请使用global关键字。

于 2013-05-11T22:39:30.047 回答
1

您需要使用global语句。这些都比较简单。为此,只需在定义变量本身之前将变量定义为全局变量。例如:

def setcake(taste):
    global cake
    cake = taste
def caketaste():
    print cake 
setcake('tasty')
caketaste() #Output is tasty

编辑:对不起,我似乎误读了你的问题。请允许我现在尝试正确回答。

def printcake():
    print cake #This function prints the taste of cake when called
def setcake(taste, printq):
    global cake #This makes sure that cake can be called in any function
    cake = taste #sets cake's taste
    if printq: #determines whether to print the taste
        printcake() 
setcake('good', True) #Calls the function to set cake. Tells it to print result. The output is good

输出,如代码所示:http: //ideone.com/dkAlEp

于 2013-05-11T22:56:42.503 回答