【问题标题】:How to import python package with two files with 'from ... import ...' statement如何使用'from ... import ...'语句导入带有两个文件的python包
【发布时间】:2019-10-27 12:26:30
【问题描述】:

我的目录如下所示:

test.py
foo/
    __init__.py
    foo.py
    bar.py

bar 是一个 python 类,看起来像这样:

class Bar:
...

foo 只是一个脚本,看起来像这样:

from foo.bar import Bar
def fun1():
...

初始化

现在在 test.py 我要导入包并访问 fun1() 如下:

from foo import foo
fun1()

但是这失败了。我只能这样调用 fun1()

foo.fun1()

我已经阅读了数十篇关于 python 包/模块/导入的帖子和文章,但我似乎无法弄清楚我应该做什么...:/

我很乐意提供任何帮助!

【问题讨论】:

    标签: python-3.x import package python-module


    【解决方案1】:

    你只需要放入你的 __init__.py 文件

    from .foo import fun1
    

    test.py 中你可以这样做:

    from foo import fun1
    
    ...
    fun1()
    

    【讨论】:

      【解决方案2】:

      如果我猜对了,你可以试试:

      from foo import foo as f
      import f.fun1()
      

      那么你可以称它为

      fun1()
      

      【讨论】:

        猜你喜欢
        • 2020-04-26
        • 2018-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多