Python:如何从导入的模块调用全局函数 [英] Python : How to call a global function from a imported module

查看:60
本文介绍了Python:如何从导入的模块调用全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Python 3 中从导入的函数中调用全局函数?

Would it be possible to call a global function from imported function in Python 3?

./folders/folder1/def.py

./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

显然,如果在同一个文件中定义相同的函数就可以正常工作.

Apparently, the same functions works just fine if defined in the same file.

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 不允许这样做,那么最接近的替代方案是什么?在我的实际项目中,全局函数可以访问全局变量.如果可能的话,我想避免将所有全局函数和变量在一个单独的类中.

If Python doesn't allow this, what would be the closest alternative ? In my real project, the global functions has number of accesses to the global variables. If all the possible, I'd like to avoid putting all the global functions and variables in a separate class.

以上是突出显示我的问题的代码摘录.在我的真实项目中,

EDIT : The above is the code excerpt to highlight my problem. In my real project,

  1. 我有十几个全局函数.因此,不建议通过函数参数传递其指针.
  2. 我在多个文件夹中有许多其他 def.py 文件.我需要根据各种条件在运行时获取 def.py 文件.因此,不推荐从 main.py 到 def.py 的静态引用.

推荐答案

我能够让main.py使用以下设置.

I was able to getmain.pyto work with the following set-up.

(请注意,我必须在 foldersfolder1 子目录中添加一个空的__init__.py文件才能使导入工作.)

(Note I had to add an empty__init__.pyfiles to both thefoldersandfolder1subdirectories to get the imports to work.)

文件.\class2\folders\folder1\def.py

File .\class2\folders\folder1\def.py

from main import global_function_1

def do_test():
    print("++ def.do_test()")
    global_function_1()
    print("-- def.do_test()")

文件.\class2\main.py

File .\class2\main.py

import importlib

def global_function_1():
    print("doing function 1 thing...")

if __name__ == '__main__':
    mod = importlib.import_module('folders.folder1.def')
    mod.do_test()

输出:

++ def.do_test()
doing function 1 thing...
-- def.do_test()

这篇关于Python:如何从导入的模块调用全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆