【发布时间】:2020-04-23 12:00:47
【问题描述】:
是否可以在 Python 3 中从导入的函数调用全局函数?
./folders/folder1/def.py
def do_test():
print("++ def.do_test()")
global_function_1()
print("-- def.do_test()")
./main.py
import importlib
def global_function_1():
print("doing function 1 thing...")
mod = importlib.import_module('folders.folder1.def')
mod.do_test()
我有这样的错误。
++ def.do_test()
Traceback (most recent call last):
File "C:\src\python\class2\main.py", line 10, in <module>
mod.do_test()
File "C:\src\python\class2\folders\folder1\def.py", line 4, in do_test
global_function_1()
NameError: name 'global_function_1' is not defined
显然,如果在同一个文件中定义相同的函数就可以正常工作。
def global_function_1():
print("calling the global function 1")
def do_test():
print("++ def.do_test()")
global_function_1()
print("-- def.do_test()")
do_test()
结果是
++ def.do_test()
calling the global function 1
-- def.do_test()
如果 Python 不允许这样做,那么最接近的选择是什么? 在我的真实项目中,全局函数具有对全局的访问次数 变量。如果可能的话,我想避免把所有的全局函数 和变量在一个单独的类中。
编辑:以上是突出我的问题的代码摘录。在我的真实项目中,
- 我有十几个全局函数。因此,不建议通过函数参数传递其指针。
- 我在多个文件夹中有十几个其他 def.py 文件。我需要根据各种情况在运行时获取 def.py 文件。因此,不推荐从 main.py 到 def.py 的静态引用。
【问题讨论】:
-
将
from main import global_function_1添加到def.py有什么问题吗? -
您的问题中的代码中没有类,那么这与您的问题标题中的“来自类”有什么关系?
-
@Rawing -- 感谢您的建议。我把我的结果放在下面的 SmeltQuake 的回答中,他给了我同样的建议。
-
@martineau --- 你是对的。我混淆了另一种类型的实现。我只是纠正了这个问题。谢谢!
标签: python namespaces