最近在考慮編碼風格的問題,突然想到如何在一個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引用的,那么該模塊中的變量就是可以被共享的。
============================================