[英]python module imports issue
here's a picture of my directory structure: 这是我的目录结构的图片:
parts.py
machine/
__init__.py
parts.py
I have a directory (a package) called machine 我有一个名为machine的目录(一个软件包)
in it there is __init__.py and parts.py 其中有__init__.py和parts.py
at the same level as machine, there is a file named parts.py 与计算机处于同一级别,有一个名为parts.py的文件
in parts.py, the code looks like this: 在parts.py中,代码如下所示:
#parts.py
class Parts(object):
pass
in machine.parts the code looks like this 在machine.parts中,代码看起来像这样
#machine.parts
from parts import Parts
class MachineParts(Parts):
pass
When I try to import machine.parts, I get an import error. 当我尝试导入machine.parts时,出现导入错误。 I don't want to change my directory structure.
我不想更改目录结构。 How should I fix this and retain good PEP8 style?
我该如何解决这个问题并保持良好的PEP8风格?
You should make it a package by adding top-level __init__.py
and giving some meaningful name to top-level directory: 您应该通过添加顶级
__init__.py
并将其赋予顶级目录一些有意义的名称来使其成为一个包:
mypackage
__init__.py
parts.py
machine/
__init__.py
parts.py
Then, use absolute imports: 然后,使用绝对导入:
#machine.parts
from mypackage.parts import Parts
class MachineParts(Parts):
pass
Since import
supports relative imports, try: 由于
import
支持相对导入,请尝试:
from ..parts import Parts
Another option is to use an absolute import: 另一种选择是使用绝对导入:
from appname.parts import Parts
As mentioned in How to import a Python class that is in a directory above? 如如何导入上面目录中的Python类中所述?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.