2017-08-02 101 views
0

例如,我有一个名为myproject的项目。在myproject目录中。有other子目录和main.py。并且在other子目录中,有a.pyb.py如何组织python的项目结构?

a.py内容是

import b 

main.py内容是:

from other.a import * 

又来了一个问题,在main.py,当我使用from other.a import *a.py的内容包括在main.py,它会引发错误,因为b.pyother,所以在main.py使用import b是错的,我们应该用import other.b,但是a.py需要import b,所以这是矛盾的。我该如何解决它?

+3

可能重复的[Python项目结构和相对导入](https://stackoverflow.com/questions/34732916/python-project-structure-and-relative-imports) –

+1

@MartinAlonso您链接的问题是非常不同这个。 –

+0

您不应该使用包内的相对导入。在Python 3中,它们不起作用,在Python 2中它们已被弃用。所以在'a.py'你需要做'from'。导入b'或'import other.b'。 –

回答

1

我认为这是你的代码结构,对吗?

mypackage 
    other 
     __init__.py 
     a.py # import b 
     b.py # def func_b() 
    __init__.py 
    main.py # from other.a import * 

您可以使用此代码结构:

请不要在安装包中使用绝对导入,如:from mypackage.other import bmain.py,使用相对进口如:main.pyfrom .other import b。因为这样做,当你有一个脚本test.py

from mypackage import main 

main.b.func_b() 

底层它from .other.a import *

b.func_b(...) 

,因为你有:

mypackage 
    other 
     __init__.py 
     a.py # from . import b 
     b.py 
    __init__.py 
    main.py # from .other.a import * 

那么您可以在main.py做到这一点from . import b in a.py。所以*实际上是b,这就是为什么你可以使用b.func_b()in main.py