Python3.10.6
假设您有以下文件:
main.py
setter.py
Folder/shared.py
这些内容包括:
# Folder/shared.py
class Shared:
i = 0 # something that is used in multiple locations
# setter.py
from Folder.shared import Shared
def set_i():
global Shared
print("mem in setter: " + hex(id(Shared.i)))
Shared.i = 2 # set the shared resource
# main.py
IMPORT_VIA_PATH = False
if IMPORT_VIA_PATH:
import sys, os
pwd = os.path.dirname(os.path.abspath(__file__))
shared_path = pwd + '/Folder'
sys.path.insert(0, shared_path)
from shared import Shared
else:
from Folder.shared import Shared
from setter import set_i
set_i()
print(Shared.i)
print("mem in main: " + hex(id(Shared.i)))
If IMPORT_VIA_PATH
is False
, main prints 2
for i
's value, and the memory addresses are different.
If IMPORT_VIA_PATH
is True
, main prints 0
for i
's value, and the memory addresses are the same.
更令人困惑的是,如果在整个过程中,只有i
人取代了Shared.i
人:
# Folder/shared.py
i = 0 # something that is used in multiple locations
# setter.py
from Folder.shared import i
def set_i():
global i
print("mem in setter: " + hex(id(i)))
i = 2 # set the shared resource
# main.py
IMPORT_VIA_PATH = True
if IMPORT_VIA_PATH:
import sys, os
pwd = os.path.dirname(os.path.abspath(__file__))
shared_path = pwd + '/Folder'
sys.path.insert(0, shared_path)
from shared import i
else:
from Folder.shared import i
from setter import set_i
set_i()
print(i)
print("mem in main: " + hex(id(i)))
则对于IMPORT_VIA_PATH
、True
或False
两者,i
保持零,并且存储器地址是the same.这里发生什么事情?