你好,下面有两个相同功能的运行.他们应该AB回答作为答案.但只有第一个.全局变量发生了什么?
txt=''
def test():
global txt
txt+='A'
print(txt)
return 'B'
tmp=test()
print('tmp: ', tmp)
txt+=tmp
print(txt)
Run Code Online (Sandbox Code Playgroud)
第二轮
txt=''
def test():
global txt
txt+='A'
print(txt)
return 'B'
print(txt)
txt+=test()
print(txt)
Run Code Online (Sandbox Code Playgroud)
编辑
在第二个例子中
txt += test()
Run Code Online (Sandbox Code Playgroud)
这可能会被打破
txt = txt + test()
Run Code Online (Sandbox Code Playgroud)
在这种情况下,第一个txt不会改变A.
因此,你实际上在做
txt = '' + 'B'
Run Code Online (Sandbox Code Playgroud)
对于第一个示例,txt变量已A在tmp创建过程中更改为.
因此,为了
txt += test()
Run Code Online (Sandbox Code Playgroud)
你在做 txt = 'A' + 'B'