[英]How to organize project structure of python?
例如,我有一个名为myproject
的项目。 在myproject
目录中。 还有other
子目录和main.py
在other
子目录中,有a.py
和b.py
a.py
的内容是
import b
main.py
的内容是:
from other.a import *
又来了一个问题,在main.py
,当我使用from other.a import *
,的内容a.py
包括在main.py
,它会产生一个错误,因为b.py
是other
,所以在main.py
使用import b
是错误的,我们应该使用import other.b
,但是a.py
需要import b
,因此这是矛盾的。 我该如何解决?
我认为这是您的代码结构,对吗?
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 b
main.py
from mypackage.other import b
,使用相对的导入例如: main.py
中的main.py
from .other import b
。
mypackage
other
__init__.py
a.py # from . import b
b.py
__init__.py
main.py # from .other.a import *
那么您可以在main.py中执行以下操作:
b.func_b(...)
因为这样做,当您拥有脚本test.py
from mypackage import main
main.b.func_b()
它的基础是from .other.a import *
,因为您from . import b
from . import b
a.py
。 所以*
实际上是b
,这就是为什么可以in main.py
使用b.func_b()
in main.py
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.