【问题标题】:Import sequences in Python 3.7在 Python 3.7 中导入序列
【发布时间】:2018-07-11 22:12:13
【问题描述】:

我想用这种结构组织一个包:

/program.py
/__init__.py
/data/
/data/__init__.py
/data/method_1.py
/data/method_2.py
/data/classes.py

程序导入method_1和method_2,method_1和method_2导入类。但我收到一个错误:ModuleNotFoundError:没有名为“method_1”的模块。我应该如何组织这个包以及我应该在 init.py 文件中写什么?

program.py:

import __init__
from data import classes
from data import method_1
from data import method_2
...


__init__.py:

__all__ = ['data']
from data import *


/data/__init__.py:

__all__ = ['classes', 'method_1', 'method_2']
from method_1 import *
from method_2 import *
from classes import *


/data/method_1.py: (and also /data/method_2.py)

import classes
...

【问题讨论】:

    标签: python-3.x import package


    【解决方案1】:

    method_1method_2classes are all in the data package,因此:

    # data/__init__.py
    from .method_1 import *
    from .method_2 import *
    from .classes import *
    

    ...

    # data/method_1.py
    from . import classes
    

    【讨论】:

      【解决方案2】:

      因为data 包与program 位于同一目录中,所以应该可以:

      #program.py
      from .data import classes
      from .data import method_1
      from .data import method_2
      
      # data/__init__.py
      from .method_1 import *
      from .method_2 import *
      from .classes import *
      
      
      #data/method_1.py
      from . import classes
      
      #data/method_2.py
      from . import classes
      

      【讨论】:

        猜你喜欢
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-08
        • 2022-01-09
        • 2019-12-28
        • 1970-01-01
        • 2019-02-27
        相关资源
        最近更新 更多