[英]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包main
和other_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.