[英]Import classes from submodules into (aliased) namespace
I have the following package structure: 我有以下包结构:
package_name/
__init__.py
some_module.py
another_module.py
# other classes
I'm using this package from another Python file, in which I would like to do the following: 我正在使用另一个Python文件中的此程序包,在其中执行以下操作:
declare an alias for package_name
声明package_name
的别名
import package_name as pn
and refer to classes inside some_module.py
, another_module.py
, etc. as follows: 并参考some_module.py
, another_module.py
等内部的some_module.py
,如下所示:
instance = pn.SomeClass(pn.AnotherClass(x, y))
ie omitting the module name and instead using only the package name alias. 即省略模块名称,而仅使用包名称别名。
Something like this: 像这样:
import package_name as pn
from package_name import some_module to pn
Is this, or anything equivalent, possible? 这是可能的,或等同的吗?
I can do this: 我可以做这个:
from package_name.some_module import SomeClass
from package_name.another_module import AnotherClass
instance = SomeClass(AnotherClass(x, y))
and this: 和这个:
import package_name.some_module
import package_name.another_module
instance = pn.some_module.SomeClass(pn.some_module.AnotherClass(x, y))
but this doesn't work 但这不起作用
import package_name.some_module as pn
import package_name.another_module as pn
instance = pn.SomeClass(pn.AnotherClass(x, y))
because the second as pn
overrides the first one. 因为第二个as pn
优先于第一个。
The syntax to import a single module from the package is: 从包中导入单个模块的语法为:
from package_name import some_module as pn
To have access from package_name
to the classes defined inside the other modules, the right thing to do is to import these classes, explictly or using some tool, to the __init__.py
file inside package_name: 要从package_name
访问其他模块中定义的类,正确的做法是将这些类显式或使用某种工具导入package_name中的__init__.py
文件:
package_name/__init__.py
: package_name/__init__.py
:
from .some_module import a_class
from .another_module import another_class
And that will allow you to simply do: 这将使您可以简单地执行以下操作:
import package_name as pn
pn.a_class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.