有没有办法在importee中获取importer的变量?

2024-05-12 23:52:09 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个python文件

 # importer.py
 parameter = 4
 import importee

以及

 # importee.py
 print parameter

我能或怎样才能在导入.py访问进口商.pyparameter?你知道吗

我用了一个丑陋的工作,借(和污染)的sys

 # importer.py
 import sys
 sys.parameter = 4
 import importee

以及

 # importee.py
 print sys.parameter

太难看了。 寻找更好的解决方案。你知道吗


Tags: 文件pyimportparametersys解决方案printimporter
1条回答
网友
1楼 · 发布于 2024-05-12 23:52:09

实现我认为您想要实现的功能的推荐方法是在importee中声明函数,并调用它,例如:

# importer.py
import importee
importee.call_me(4)

以及:

# importee.py
def call_me(parameter):
    print(parameter)

最好避免在全局范围内执行任何操作。尤其是print()任何东西,但我认为您的最小示例与您的实际用例不匹配:)。你知道吗


顺便说一下,您提到的难看的工作实际上相当于使用一个单独的配置模块。例如:

# importer.py
import config
config.param = 4
import importee

+

# importee.py
import config
print(config.param)

+

# config.py
param = 7 # some default

它还远没有达到完美的程度,但至少避免了与系统模块的冲突。你知道吗

相关问题 更多 >