【问题标题】: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 中的文件架构的情况下在不同的模块/类中使用模块/类函数/方法?
【发布时间】: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 作为参数传递给 ma​​in.py

中的 func2
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 完全独立并避免任何导入。

【问题讨论】:

    标签: python import


    【解决方案1】:

    您可以导入所需项目的文件名,例如: “如果我想使用名为'main.py'的文件的另一个def函数,那么我会写

    import main
    main.call_func1()
    

    【讨论】:

    • 感谢您的建议,但这并不能解决我的问题。我所有的操作都是主要的。我的主要问题是在模块 2 中的模块 1 中访问函数,而它们彼此不知道,同时避免任何导入。
    猜你喜欢
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多