覆盖一个全局变量

Overwrite a global variable

我是从 开始基础知识的,但我不知道如何更新全局变量。 代码是:

def spam():
    global eggs
    eggs='spam'
def update_eggs():
    global eggs;eggs='global'
print(eggs)

我想用“global”覆盖设置为“spam”的“eggs”变量,我尝试了这个post中的方法:Overwrite global var in one line in Python? 但它没有用。你能建议一下吗? 先感谢您! 西尔维娅

global 关键字允许您修改当前范围之外的变量。它用于创建全局变量并在局部上下文中更改变量。

在引用全局变量之前,最好在主上下文中初始化它。

eggs = "global" # <-- global variable initialized

def spam():
    global eggs
    eggs = 'spam'

def update_eggs():
    global eggs
    eggs = 'update'

print(eggs)
spam()        # <-- updates global eggs variable
print(eggs)
update_eggs() # <-- updates global eggs variable
print(eggs)

输出:

global
spam
update

调用 spam() 或 update_eggs() 都会更新全局变量 eggs.

你需要调用它的函数来执行里面的代码。

eggs = 'something'
def spam():
    global eggs
    eggs='spam'
def update_eggs():
    global eggs;eggs='global'

spam() <-- Call function
print(eggs)

这将(用箭头标记)调用垃圾邮件函数,以便将鸡蛋更新为垃圾邮件。希望这有帮助。

此外,您似乎没有定义全局变量“eggs”。您需要在代码开头提及 eggs = "something here"。 “global”命令使得定义的函数能够在你定义它之后编辑全局变量eggs。