简体   繁体   English

Python:从__init__中的模块import *

[英]Python : from module import * in __init__

Here is a simple case: I want to define a module in python name robot. 这是一个简单的案例:我想在python name robot中定义一个模块。 So, I have a folder named robot with these two files: 因此,我有一个名为robot的文件夹,其中包含以下两个文件:

__init__.py: __init__.py:

from test import a

test.py: test.py:

a = "hello world"

Now, when I import robot in the interpreter, the robot namespace includes test and a . 现在,当我在解释器中import robot时, robot名称空间包括testa However, I only want it to include a . 但是,我只希望它包含a Why this odd behavior? 为什么会有这种奇怪的行为?


EDIT: 编辑:

Here's a slightly more representative example of what I want to achieve: 这是我想要实现的一个更具代表性的示例:

Given the following files: 给定以下文件:

__init__.py: __init__.py:

from spam import a
import ham

spam.py: spam.py:

a = "hello world"

ham.py: ham.py:

b = "foo"

Can I have a robot namespace containing a and ham at its top level but not spam ? 我能有一个robot包含命名aham在其顶部水平,但不是spam

You have created not just a module but a package. 您不仅创建了模块,还创建了包。 A package contains its submodules in its namespace (once they have been imported, as you imported test here). 程序包在其名称空间中包含其子模块(一旦您导入了此处的test ,就将其导入)。 This is as it should be, since the usual way of using packages is to provide a grouping of several modules. 这是应该的,因为使用软件包的通常方法是提供几个模块的分组。 There's not much use to making a package with only one module (ie, one contentful .py file) inside it. 制作一个仅包含一个模块(即一个内容丰富的.py文件)的程序包并没有多大用处。

If you just want a one-file module, just create a file called robots.py and put your code in there. 如果只需要一个文件模块,则只需创建一个名为robots.py的文件,然后将代码放入其中即可。

Edit: See this previous question . 编辑:请参阅上一个问题 The answer is that you should in general not worry about excluding module names from your package namespace. 答案是,您通常不必担心从包名称空间中排除模块名称。 The modules are supposed to be in the package namespace. 这些模块应该位于包名称空间中。 If you want to add functions and stuff from submodules as well, for convenience, that's fine, but there's not really anything to be gained by "covering your tracks" and hiding the modules you imported. 如果您也想从子模块中添加功能和内容,那很好,但是“覆盖轨道”并隐藏导入的模块并没有任何实质意义。 However, as described in the answers to that question, there are some hackish ways to approximate what you want. 但是,如该问题的答案中所述,有一些骇人听闻的方法可以近似您想要的内容。

Are you just asking how to import specific modules or functions? 您是在问如何导入特定的模块或功能吗?

test.py: test.py:

import robot.spam.a
import robot.ham

Don't import the entire package. 不要导入整个程序包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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