简体   繁体   English

从位于python包中的文件导入特定的类

[英]Importing specific classes from a file located in a python package

I have a python package main and other_python_files which are like: 我有一个python包mainother_python_files ,它们是:

main/
    __init__.py
    lib.py
    other_python_files/
        __init__.py
        test.py

Let lib.py contain a class called MyClass . lib.py包含一个名为MyClass的类。 When I do from main import lib.py and use MyClass inside test.py I get the error that MyClass is not defined. 当我from main import lib.py并在test.py使用MyClass ,我得到MyClass未定义的错误。

I tried doing from main import MyClass inside the init file in the main directory but I still get the same error. 我试图做from main import MyClass初始化文件中的main目录,但我仍然得到同样的错误。 What should I do to achieve importing a specific class from the lib.py file ? 如何从lib.py文件中导入特定的类?

You either have to import that class out of lib : 你要么必须从lib导入该类:

from main.lib import MyClass

Or use lib.MyClass in place of MyClass . 或者使用lib.MyClass代替MyClass

You can also import MyClass inside of the __init__.py file that's in main , which lets you import it the way you originally tried: 您还可以在main中的__init__.py文件中导入MyClass ,这样您就可以按照最初尝试的方式导入它:

__all__ = ['MyClass']

from lib import MyClass

You can read about __all__ here: Can someone explain __all__ in Python? 你可以在这里阅读__all__有人可以在Python中解释__all__吗?

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

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