[转载]python跨文件使用全局变量的实现

python跨文件使用全局变量的实现

更新时间:2022-10-25 14:46:38发布时间:602天前

Python 定义了全局变量的特性,使用global 关键字修饰

1
global key_word

但是他的一大缺陷就是只能本module 中也就是本文件中使用,跳出这个module就不行。

try 1:
使用一个更宏观的思路,全局变量就用全局加载的模块解决,很遗憾也是不行,

file_1:

1
2
global a
= "test"

file 2:

1
2
import file_1
print(a)

报错a没有定义
try 2:
file_1:

1
2
global a
= "test"

file 2:

1
2
3
4
import file_1
print(file_1.a)
file_1.a = "aaa"
print(file_1.a)

这样可以,但是如果再有一个module 想用呢?
try 2:
file_1:

1
2
global a
= "test"

file 2:

1
2
3
4
import file_1
print(file_1.a)
file_1.a = "aaa"
print(file_1.a)

file 2:

1
2
3
4
5
import file_1
import file_2
print(file_1.a)
file_1.a = "aaa"
print(file_1.a)

这样就会报错,因为import 加载就会执行一遍子module ,两个module y引用关系死锁了。

try 3:
 最终使用公共数据结构方式解决

file_1:

1
2
3
4
5
6
7
def init():
 global a
 = {}
def set(arg,value):
 a[arg] = value
def get(arg)
 return a[arg]

file 2:

1
2
3
import file_1
print(file_1.a)
file_1.set("test",(test_value))

file 2:

1
2
3
4
5
import file_1
import file_2
file_1.init()
 
print(file_1.get("test"))

思路就是使用一个公共的字典的数据结构,在主module 中初始化,其他module都应用此module,但是不重新初始化字典。

到此这篇关于python跨文件使用全局变量的实现的文章就介绍到这了,更多相关python跨文件全局变量内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

 
转载请注明:文章转载自 www.kaotop.com
posted @ 2022-10-25 14:47  workingdiary  阅读(1620)  评论(0编辑  收藏  举报