[英]Python - Can I import specific classes when importing all from a package
I have a package set up with a tree structure like 我有一个像树形结构的软件包
pkg\
__init__.py
module1.py
Class11
Class12
module2.py
Class21
function21
I want specific classes and functions to be in the global namespace such that when I start my script with 我希望特定的类和函数位于全局名称空间中,以便当我使用以下命令启动脚本时
from pkg import *
I will be able to directly use, say, Class11, Class12, and function21. 我将能够直接使用Class11,Class12和function21。 Is this possible?
这可能吗? The motivation behind it is to allow for quick and light usages in small scripts or interactive mode.
其背后的动机是允许在小型脚本或交互模式下快速轻松地使用。 It's implicitly known that with longer scripts one would not use import all and traverse the package structure properly.
隐含地知道,使用更长的脚本时,将不会使用全部导入并正确遍历包结构。
EDIT: I could import Class11, Class12, and function21 in pkg's __init__.py
, but in this way, when I do the regular import pkg
I will still be able to access Class11 by pkg.Class11
instead of the proper pkg.module1.Class11
. 编辑:我可以在pkg的
__init__.py
导入Class11,Class12和function21,但是通过这种方式,当我执行常规import pkg
我仍然能够通过pkg.Class11
而不是适当的pkg.module1.Class11
访问Class11。 。 Preferably I want pkg.module1.Class11
to be the only way if I'm not doing import *
. 如果我不执行
import *
则最好让pkg.module1.Class11
是唯一方法。
Sure. 当然。 The
*
means "everything". *
表示“一切”。 * If you don't want everything, but instead want a specific list of names, just use those names: *如果您不想要所有内容,而是想要一个特定的名称列表,请使用这些名称:
from pkg import Class11, Class21, function21
Of course this assumes that pkg
already imports those names from its submodules. 当然,这假定
pkg
已经从其子模块中导入了这些名称。 But if that weren't true, your *
import wouldn't work either. 但是,如果那不是真的,那么您的
*
导入也不起作用。
If that isn't true, but you want to know how to make it true, you just do something similar in pkg/__init__.py
: 如果那不是真的,但是您想知道如何实现,那么只需在
pkg/__init__.py
执行类似的pkg/__init__.py
:
from .module1 import Class11, Class12
from .module2 import Class21, function21
Or, maybe: 或者可能:
from .module1 import __all__ as _all1
from .module2 import __all__ as _all2
from .module1 import *
from .module2 import *
__all__ = _all1 + _all2
* Well, not quite "everything". *嗯,不是“一切”。 If there's an
__all__
, it means "every name in __all__
"; 如果有
__all__
,则表示“ __all__
每个名称”; if not, it means "every name that doesn't start with _
". 如果不是,则表示“每个不以
_
开头的名称”。 But close enough for our purposes. 但是足够接近我们的目的。
Set up your __init__.py
like this: 像这样设置
__init__.py
:
from .module1 import Class11, Class12
from .module2 import Class21, function21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.