繁体   English   中英

如何组织python的项目结构?

[英]How to organize project structure of python?

例如,我有一个名为myproject的项目。 myproject目录中。 还有other子目录和main.py other子目录中,有a.pyb.py

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 ,因此这是矛盾的。 我该如何解决?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM