Python相对导入和包 [英] Python Relative Imports and Packages

查看:139
本文介绍了Python相对导入和包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个包,我有一个如下所示的树结构:

I'm trying to create a package and I have a tree structure that looks like this:

dionesus/
  setup.py
  dionesus/
    __init__.py
    dionesus.py

Dionesus.py有一个名为Dionesus的课程。 init .py为空。

Dionesus.py has a class called Dionesus. The init.py is empty.

如何在不指定顶级文件夹的情况下导入Dionesus类?

How do I import the class Dionesus without having to specify the top level folder?

我必须这样做:

import dionesus
d = dionesus.dionesus.Dionesus()

我想将import语句看起来像:

I would like import statements to look like:

import dionesus
d = dionesus.Dionesus()


推荐答案

首先,您仍然可以使用绝对导入,只需使用 from ... import 表单:

First, you can still use an absolute import, just using the from … import form:

from dionesus import dionesus
d = dionesus.Dionesus()

如果您需要在同一个模块中导入dionesus和dionesus.dionesus,这显然会有问题,但这几乎是隐含于希望同时给它们两个没有消除歧义的名字...

This will obviously be problematic if you ever need to import both dionesus and dionesus.dionesus in the same module, but that's pretty much implicit in the desire to give them both the same non-disambiguated name…

或者,如果你是父母或兄弟姐妹或其他亲属的dion esus.dionesus,你可以使用相对导入。根据你所处的位置,它会有所不同(毕竟这是相对的意思);您可能从 .dionesus .. ,等等。但无论它在哪里,它都与上面的...... import 表格相同,只是使用相对名称而不是绝对名称。 (事实上​​,相对导入总是使用表格中的。)

Alternatively, if you're in a parent or sibling or other relative of dionesus.dionesus, you can use a relative import. Depending on where you are, it'll be different (that's what relative means, after all); you may be importing from ., .dionesus, .., etc. But wherever it is, it's the same from … import form as above, just with a relative name instead of an absolute one. (In fact, relative imports always use the from form.)

from . import dionesus
d = dionesus.Dionesus()

这篇关于Python相对导入和包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆