[英]How can I modify a variable in one file and use it in another file?
I would like to:我想:
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.