如何直接从Python包中导入类

huangapple go评论60阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2023年3月3日 20:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定