最近在考虑编码风格的问题,突然想到如何在一个python应用下的多个模块中共享一个变量。最早接触python还是在python2.5版本左右,那个时候由于python的import规则设定的问题导致本文所提问题难以解决,这也是不知不觉中都到了python3.10的版本了,由于python3中对python的import规则进行了修改,从而是python多模块下共享变量变得容易了。 本文问题的解决主要依赖于python3采用绝对路径的命名空间。
给出示例:
代码文件层级关系的结构:
说明:
main.py 是我们要运行的主文件,sub_module模块是与main.py同级的,二者在同一目录下。
test 模块 和 x.py y.py __init__.py 这四个文件在同一目录下,为同级关系。其中,__init__.py 文件为空文件。
给出 x.py , y.py 的文件内容:
x.py
print("enter x file") from . import test print( test.x, test.x.x, test.x.y, ) test.x.x=15 test.x.y=15 print( test.x, test.x.x, test.x.y, ) print("exit x file")
y.py
print("enter y file") from . import test from .test import * print( test.x, test.x.x, test.x.y, ) test.x.x = 20 test.x.y = 20 print( test.x, test.x.x, test.x.y, ) print("exit y file")
test 模块下的 __init__.py 文件内容:
print("enter test.init file") class X: def __init__(self, x: int, y: int): self.x=x self.y=y x = X(11, 11) print(x, x.x, x.y) print("exit test.init file")
====================================
运行 main.py 文件:
运行结果:
enter test.init file <sub_module.test.X object at 0x7ff5eebc5050> 11 11 exit test.init file main file: <sub_module.test.X object at 0x7ff5eebc5050> 11 11 enter x file <sub_module.test.X object at 0x7ff5eebc5050> 11 11 <sub_module.test.X object at 0x7ff5eebc5050> 15 15 exit x file enter y file <sub_module.test.X object at 0x7ff5eebc5050> 15 15 <sub_module.test.X object at 0x7ff5eebc5050> 20 20 exit y file main file: <sub_module.test.X object at 0x7ff5eebc5050> 20 20
============================================
从上面的运行结果可以看出python3版本的命名空间都是绝对路径的,也就是说一个模块中定义的变量在另一个模块中只要是可以import引用的,那么该模块中的变量就是可以被共享的。
============================================