【发布时间】:2021-07-09 17:55:53
【问题描述】:
我是一名中级 Python 程序员,但有些事情困扰了我一段时间。我正在尝试统一代码以使其可被许多项目重用。我面临的问题是如何在不导入模块/类的情况下通过某个类(或过程代码)访问函数(或相关的方法)。我希望我的代码不知道其他文件/模块的存在。 这是一个例子。
假设我的项目有以下文件架构(其他项目可以重用,但略有不同):
- 主文件夹
- main.py
- 文件夹 1>module1>func1
- Folder2>module2>func2(func2 调用 func1,假设 func1 是一种常见的数学运算,例如查找一个点是否在公差范围内的平面上)
现在,在 main.py 中,我同时导入了 module1 和 module2
假设我在 main.py 中有一个这样调用 func2 的函数
## In main.py
def call_func1():
module2.func2()
## In module1.py
def is_point_on_plane():
print("testing")
## In module2.py
def func2():
is_point_on_plane() ## This is a function that is currently in module1
现在,我不希望 module1 或 module2 知道彼此的任何信息,甚至不希望知道对方的存在。我试图避免任何进口。
我解决这个问题的方法是将 is_point_on_plane 作为参数传递给 main.py
中的 func2def call_func1():
fcToCall = module1.is_point_on_plane
module2.func2(fcToCall)
## In module1
def is_point_on_plane():
print("testing")
## In module2
def func2(fcToCall):
fcToCall()
我确信有更好的方法来做到这一点。一种更 Pythonic 的方式。无论哪种情况,我都需要 module1 和 module2 完全独立并避免任何导入。
【问题讨论】: