每个函数的全局变量

Global variable for each function

我有很多函数,它们都编辑了一些变量,但我希望每个函数都编辑以前编辑过的变量(通过先前的函数):

text = "a"    
def a():
        text + " hi"
        print(text)
def b():
       text + " there"
       print(text)
def main():
      a()
      b()
main()

^所以当 运行 main 时,我希望它出现:

>>a hi
>>a hi there

我试过全局,但似乎无法正常工作

即使使用 global,您仍然需要 re-assign 一个新值 到全局变量 - 在您的情况下 texttext + " hi" 只是创建一个新字符串并将其丢弃。使用 global text,然后也执行 text = 'text' + <string>

text = "a"    

def a():
    global text
    text = text + " hi"
    print(text)

def b():
    global text
    text = text + " there"
    print(text)

def main():
      a()
      b()
main()

以上现在输出:

a hi
a hi there

使用global重新分配文本变量

text = "a"    
def a():
    global text
    text += " hi"
    print(text)
def b():
    global text
    text += " there"
    print(text)
def main():
    a()
    b()
main()

结果

a hi
a hi there