导入文件中未修改全局变量

2024-09-28 20:56:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个程序分成两个文件,如下所示:

# fileA.py
from fileB import *
add_a_bit_on_the_end()
print("Hello from file A.\nstringvar = [" + stringvar + "]")

# fileB.py
stringvar = "this var was initialised in file B"

def add_a_bit_on_the_end():
    global stringvar
    print("stringvar was ["+stringvar+"]")
    stringvar += " added extra bit"
    print("but now it has become ["+stringvar+"]")

当我运行fileA.py时,我得到

stringvar was [this var was initialised in file B]
but now it has become [this var was initialised in file B added extra bit]
Hello from file A.
stringvar = [this var was initialised in file B]

Process finished with exit code 0

为什么“多余的部分”丢失了


Tags: infrompyaddonvarbitthis