![](/img/trans.png)
[英]How to access to calling module namespace from called module in Python?
[英]How to access to the variables of the scope of a module called from the main module?
我需要訪問從其他模塊導入到主模塊中的模塊范圍的變量。
在我的應用程序中,我在同一目錄中有一些模塊。 這些模塊之一是使用configparser讀取config_file.ini以便加載使用其他模塊的配置變量的模塊。
我不想多次導入管理config_file.ini的模塊,以避免避免兩次打開同一文件的問題。
我不在管理config_file.ini的模塊中使用函數或分類(僅用於更新文件的函數),但未加載變量。
圖形概念:
Module_A:
# !usr/bin/python3
# -*- coding: UTF-8 -*-
import module_B
import module_C
print(module_B.my_var)
print(module_C.my_var)
Module_B:
# !usr/bin/python3
# -*- coding: UTF-8 -*-
my_var = "This is the Module B"
Module_C:
# !usr/bin/python3
# -*- coding: UTF-8 -*-
my_var = "This is the Module C"
print(module_B.my_var)
我正在使用Python3.x
我應該將它們封裝在單獨的類中嗎? 我沒有OOP經驗:-(
模塊僅加載一次; 后續導入將重用已經導入的模塊 。
換句話說,只需將config.ini
加載到一個模塊中,然后將變量從該模塊導入其他模塊即可。
如果要訪問Module_C中的Module_B.my_var,則需要在Module_C中import Module_B
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.