python中文件之间共享变量:为什么每当文件使用变量时都会修改变量



[edit]我将testons_constants重命名为testons_variables,以更清楚地表明我希望能够修改变量。如果注释中出现testons_constants,请考虑它对应于新名称testons_variables

我试图了解python中的变量是如何在文件之间共享的。

我为此制作了三个文件:

测试.py:

import testons_variables
import testons_functions
# The goal of this file is to understand how python deals with variables shared between files 

print(testons_variables.A) # We can access the variable from the other file
testons_variables.A=5 # We can modify its value
print(testons_variables.A)
testons_functions.fct()
print(testons_variables.A) # The value has been modified from testons_functions

testons_variables.py:

A=0

testons_functions.py

import testons_variables
def fct():
print(testons_variables.A) # this print will show the value of the variable from testons before the call of the function, and not from
# testons_variables
testons_variables.A=50 # We can modify the value
print(testons_variables.A) 

以下是我运行testons.py时的输出:

0
5
5
50
50

现在,做";反向理解";,我意识到,无论在哪里修改变量testons_variables.A,它都会被修改为所有使用它的文件。事实上,如果我在文件testons.py中修改它,它也会在testons_functions.py中被修改。如果我在testons_functions.py

这是我现在的理解。因此,无论在哪里进行了修改,文件之间共享的变量似乎都会为每个人进行修改。

让我困惑的是,如果我们使用全局变量,要在函数中修改它们,我们需要关键字";全局";以允许全局修改。我从来没有在这里用过这样的关键词。我知道情况并不完全相同(我没有在唯一文件中的函数内部使用全局变量(,但无论如何,我对这种行为感到不安,这让我认为我可能遗漏了一点。

然后我想知道我是否正确理解当变量在文件之间共享时会发生什么,这是我的问题

仅在teston.pyteston_functions.py中打印导入的teston_variables的引用

print(id(testons_variables))

您会注意到,两个print语句都提供相同的值,因此,尽管它们在不同的位置导入,但它们使用相同的引用。

这意味着一个内存位置的变化会影响其他内存位置,因为它们指向相同的内存位置。

现在,关于global关键字的用法,只有当您需要更改变量的值并且没有作用域时,它才有用。

模块也是对象。当您在函数范围之外的模块中定义变量时,它属于该模块。它不是全球性的。

当您导入一个模块时,您会得到与其他导入该对象的人相同的模块对象。Python缓存模块,因此无论导入多少次或多少个位置,都只能得到一个包含该模块的对象。因为该模块是共享的,所以该模块中的所有变量也是共享的。

最新更新