[英]How to use a module/class function/method in a different module/class without importing the module/class or knowing the file architecture in Python?
我是一名中级 Python 程序员,但有一些事情一直困扰着我。 我正在尝试统一代码以使其可被许多项目重用。 我面临的问题是如何在不导入模块/类的情况下通过某个类(或过程代码)访问函数(或与此相关的方法)。 我希望我的代码不知道其他文件/模块的存在。 这是一个例子。
想象一下,我的项目有以下文件体系结构(它将被其他项目重用,但略有不同):
现在,在 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作为参数传递给FUNC2在main.py
def 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 完全独立并避免任何导入。
你可以导入你想要的项目的文件名,例如:“如果我想使用名为'main.py'的文件的另一个def函数,那么我会写
import main
main.call_func1()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.