Python并从另一个包导入

时间:2017-02-23 04:27:04

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

我的Python版本是3.5。

我的项目结构如下:

-- test
---- __init__.py
---- one
------ __init__.py
------ first.py
---- two
------ __init__.py
------ second.py

first.py档案的内容:

class FirstClass(object):

    def hello(self):
        return 'hello'

second.py档案的内容:

def main():
    first = FirstClass()
    print(first.hello())

if __name__ == '__main__':
    main()

问题是我无法在FirstClass中导入second.py,我试过了:

from test.one.first import FirstClass

Result:

Traceback (most recent call last):
  File "second.py", line 3, in <module>
    from test.one.first import FirstClass
ModuleNotFoundError: No module named 'test.one'

另外,我尝试了这种方法:

from ..one.first import FirstClass

Result:

Traceback (most recent call last):
  File "second.py", line 3, in <module>
    from ..one.first import FirstClass
ValueError: attempted relative import beyond top-level package

所以,我的问题是:如何在这种情况下导入?

1 个答案:

答案 0 :(得分:0)

这是一个黑客但但是会起作用:

def main():
    first = FirstClass()
    print(first.hello())

if __name__ == '__main__':
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    __package__ = "one"
    from one.first import FirstClass
    main()

参见:Leon的评论链接