[英]How to access to the variables of the scope of a module called from the main module?
I need to access to the variables of the scope of a module imported in the main module from other module. 我需要访问从其他模块导入到主模块中的模块范围的变量。
In my app, I've some modules in the same directory. 在我的应用程序中,我在同一目录中有一些模块。 One of these modules is a module that read a config_file.ini using configparser in order to load the configuration variables that use the other modules.
这些模块之一是使用configparser读取config_file.ini以便加载使用其他模块的配置变量的模块。
I don't want to import more than one time the module that manages the config_file.ini in order to avoid the issues of keep open twice the same file. 我不想多次导入管理config_file.ini的模块,以避免避免两次打开同一文件的问题。
I'm not using functions nor clases in the module that manages the config_file.ini (only a function to update the file) but not to load the variables. 我不在管理config_file.ini的模块中使用函数或分类(仅用于更新文件的函数),但未加载变量。
Graphical concept: 图形概念:
Module_A: 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: Module_B:
# !usr/bin/python3
# -*- coding: UTF-8 -*-
my_var = "This is the Module B"
Module_C: Module_C:
# !usr/bin/python3
# -*- coding: UTF-8 -*-
my_var = "This is the Module C"
print(module_B.my_var)
I'm using Python3.x 我正在使用Python3.x
Should I encapsulate them in a separate class? 我应该将它们封装在单独的类中吗? I'm not experienced in OOP :-(
我没有OOP经验:-(
Modules are only loaded once; 模块仅加载一次; subsequent imports reuse the already imported module .
后续导入将重用已经导入的模块 。
In other words, just load your config.ini
in your one module, then import the variables from that module into others. 换句话说,只需将
config.ini
加载到一个模块中,然后将变量从该模块导入其他模块即可。
如果要访问Module_C中的Module_B.my_var,则需要在Module_C中import Module_B
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.