英文:
How to import class from a Python package directly
问题
在module_one.py中有ClassOne,而在module_two.py中有ClassTwo。现在,如果我想要在其他模块中导入ClassOne,我会这样写:from package.module_one import ClassOne。
是否可以直接从package中导入ClassOne,就像这样:from package import ClassOne 或者 import package as pkg,然后使用类如 pkg.ClassOne()?如果可以,如何操作?我之所以问是因为这样更加优雅。
英文:
My current package looks something like this:
package_repo/
package/
__init__.py
module_one.py
module_two.py
tests/
setup.py
Inside the module_one.py I have ClassOne,and inside the module_two.py I have ClassTwo. Now, if I want to import ClassOne into some other module, I write from package.module_one import ClassOne.
Is it possible to import ClassOne directly from package as in from package import ClassOne or import package as pkg and then use classes as pkg.ClassOne()? If yes, how to do it? I am asking because that is just more elegant.
答案1
得分: 1
在你的包的__init__.py文件中,你可以声明和初始化任何你想要的东西,包括导入!
因此,在其中写入以下内容:
from module_one import ClassOne
from module_two import ClassTwo
这样做,现在这些类将被识别并可以直接从包中导入,如下:
from package import ClassOne, ClassTwo
而且,你也可以这样做:
import package as pkg
pkg.ClassOne()
英文:
Inside the __init__.py file in your package, you can declare and initialize anything you want, including imports!
So, write inside it this:
from module_one import ClassOne
from module_two import ClassTwo
Doing so, now those classes will be known and can be imported directly from the package, as:
from package import ClassOne, ClassTwo
And yes, you can also do it like:
import package as pkg
pkg.ClassOne()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论