【发布时间】:2021-03-20 17:14:25
【问题描述】:
[编辑] 我将 testons_constants 重命名为 testons_variables 以更清楚地表明我希望能够修改变量。如果在注释中出现 testons_constants,请考虑它对应于新名称 testons_variables
我试图了解变量是如何在 python 中的文件之间共享的。
为此我制作了三个文件:
testons.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中修改,testons.py也会被修改。
这是我现在的理解。因此,文件之间共享的变量似乎对每个人都进行了修改,无论修改在哪里。
让我困惑的是,如果我们使用全局变量,要在函数中修改它们,我们需要关键字“global”来允许全局修改。我从来没有在这里使用过这样的关键字。我知道情况并不完全相同(我没有在唯一文件中的函数内部使用全局变量),但无论如何我都对这种行为感到不安,这让我觉得我可能在这里遗漏了一点。
然后我想知道我是否正确理解了在文件之间共享变量时会发生什么,这是我的问题。
【问题讨论】:
-
将变量作为参数发送给函数并返回一个值总是被认为是更好的做法。它将避免混淆和不一致。此外,您可以使用
enum来存储常量。 @StarBucK -
@Vishnudev 对于我当前的项目来说,这样做将是一场噩梦,因为我有许多类似 testons_functions 的函数(大约 200 个)。必须明确地向它们发送与参数相同的变量意味着我的代码中有大量不必要的重复。现在也许还有其他更好的方法可以继续,我有兴趣了解它们。但尽管如此,我也想检查我对这个问题的理解,即使它是编写代码的“糟糕方式”=)
-
对象(例如模块)的变异对任何引用该对象的人都是可见的。为对象分配名称是本地的(改变名称的本地
__dict__),除非使用nonlocal或global来指示所涉及的命名空间。 -
没有。这不会是重复,使用类正确构建代码,它是可以被函数访问的变量。如果您遵循全局共享变量方法,那将是一场调试噩梦。
-
stackoverflow.com/questions/14323817/… 看看这个。这应该让您知道为什么会发生这种情况。