【问题标题】:Sharing variable between files in python: why are variable modified from whenever file is using them?在 python 中的文件之间共享变量:为什么在文件使用它们时修改变量?
【发布时间】: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__),除非使用 nonlocalglobal 来指示所涉及的命名空间。
  • 没有。这不会是重复,使用类正确构建代码,它是可以被函数访问的变量。如果您遵循全局共享变量方法,那将是一场调试噩梦。
  • stackoverflow.com/questions/14323817/… 看看这个。这应该让您知道为什么会发生这种情况。

标签: python variables


【解决方案1】:

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

print(id(testons_variables))

您会注意到两个打印语句都给出相同的值,因此,尽管它们是在不同的地方导入的,但它们使用相同的引用。

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

现在,关于global关键字的使用,它只在你需要改变一个变量的值并且你没有作用域的时候才有用。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-14
      • 2011-04-24
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2015-08-08
      相关资源
      最近更新 更多