Python:从包含当前文件的文件中调用函数 [英] Python: Calling a function from a file that has current file imported

查看:313
本文介绍了Python:从包含当前文件的文件中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着四处搜寻,但似乎没有找到我的问题的答案,所以我很抱歉,如果我错过了一些东西,它实际上已经回答过。



<所以基本上我有main.py和另一个名为check.py的文件(两者都在同一个目录中)

在我的main.py中我有:

  from check import checkfunction 

我在main.py中有一个小函数,我必须在check.py中调用,但我似乎无法得到这个导入在我的check.py上工作:

  from main import main函数

如何获取主函数在check.py中工作?



谢谢!

解决方案

选项:
$ b


  • 将公共函数移动到由其他模块导入的模块中。 合并两个模块合并为一个。

  • 将函数从main传递给需要调用它的代码。


  • 重新整理所有东西,使得你没有循环依赖。

  • ul>

    如果你真的解释了为什么你有这个设计,有人可能会提出一个更好的方法。


    I tried searching around but didn't seem to find an answer to my problem, so I'm sorry if I missed something and it actually has been answered before.

    So basically I have main.py and another file called check.py (both in same directory)

    In my main.py I have:

    from check import checkfunction
    

    I have a small function inside main.py that I MUST call inside check.py, but I can't seem to get this import working on my check.py:

    from main import mainfunction
    

    How can I get the mainfunction to work inside check.py?

    Thanks!

    解决方案

    Several options:

    • Move the common function to a module imported by both other modules.
    • Merge both modules into one.
    • Pass the function from main to the code that needs to call it.
    • Monkey patch the function into the check module after importing it.
    • Refactor the whole thing so that you don't have circular dependencies.

    If you actually explained why you have this design, someone could possibly propose a better way.

    这篇关于Python:从包含当前文件的文件中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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