简体   繁体   English

如何修改一个文件中的变量并在另一个文件中使用它?

[英]How can I modify a variable in one file and use it in another file?

I would like to:我想:

  • Declare a variable in one file在一个文件中声明一个变量
  • Write its value in a second file将其值写入第二个文件
  • Read its value in a third file在第三个文件中读取它的值

Here is my minimum example:这是我的最小示例:

File "modify.py":文件“修改.py”:

from declare import *
from use import *

array = [[0 for _ in range(2)] for _ in range(2)]
print("array:")
for row in array:
    print(row)

i_hate_python()
i_really_hate_python()

File "declare.py":文件“declare.py”:

array = [[]]

def i_hate_python():
    print("array:")
    for row in array:
        print(row)

File "use.py":文件“use.py”:

from declare import *

def i_really_hate_python():
    print("array:")
    for row in array:
        print(row)

I am running the problem like so:我正在这样运行问题:

python modify.py

The output is: output 是:

array:
[0, 0]
[0, 0]
array:
[]
array:
[]

I would like the output to be:我希望 output 是:

array:
[0, 0]
[0, 0]
array:
[0, 0]
[0, 0]
array:
[0, 0]
[0, 0]

Thanks in advance for not leaving any comments about how I must be designing my program badly.提前感谢您没有留下任何关于我必须如何糟糕地设计我的程序的评论。

array = [[0 for _ in range(2)] for _ in range(2)]

That line of code in modify.py recreates array as a local variable, and you've lost the imported variable of the same name. modify.py 中的那行代码将array重新创建为局部变量,并且您丢失了同名的导入变量。

Try this instead:试试这个:

import declare
declare.array = ...

By prefixing declare.通过前缀declare. to the variable name, you keep the association with its containing module.对于变量名称,您保持与其包含模块的关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在另一个文件中使用此变量? - How do I use this variable in another file? 如何在另一个文件中使用调用文件循环变量(python) - How can I use the calling file loop variable in another file (python) 我可以从另一个.py 文件中的一个 function 打印一个变量吗 - Can I print a variable from one function in another .py file 如何在另一个文件中使用此变量 - How to use this variable in another file 如何使用一个 Python 程序将另一个程序转换为 exe 文件? - How can I use one Python program to turn another one into an exe file? 一个 python 文件如何创建另一个具有相同变量的文件 - How can one python file create another with the same variable 如何使用 tkinter 从另一个 class 修改一个 class 中使用的变量? - How can I modify a variable being used in one class from another class by using tkinter? 如何修改另一个文件中的特定变量并在其他不同的文件中使用它? - How to modify a specific variables in another file and use it in other different file? 我如何使用一个变量的值在python中调用另一个变量? - How can i use the value of one variable to call another in python? 如何在另一个python文件中的方法中使用变量的值? - How can I use the value of a variable in a method inside another python file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM