简体   繁体   English

导入程序包时,如何说服Python从子模块导入类?

[英]How can I convince Python to import a class from a submodule when you import the package?

Example: mypkg/submodule.py with class MyClass inside. 示例: mypkg/submodule.py其中包含类MyClass

I want to be able to do: 我希望能够做到:

import mypkg
obj = MyClass()

What I need to do in order to make this work with default import? 为了使此功能与默认导入配合使用,我需要做什么?

I note that from pkg import * and import pkg.submodule works are working but I want to change the behaviour of the default import . 我注意到from pkg import *import pkg.submodule可以正常工作,但是我想更改默认import的行为。

This is clearly related to __init__.py and __all__ . 这显然与__init__.py__all__

You can't do that normally (I guess with some crazy hacks it could be possible). 您通常无法做到这一点(我想可能会有一些疯狂的黑客入侵)。 You either have: 您要么有:

from mypkg.submodule import MyClass

Or if you setup __init__.py in the package appropriately, you could have: 或者,如果您在软件包中适当地设置了__init__.py ,则可能会有:

from mypkg import MyClass

It is not possible, a simple python import will only add the module to the current namespace. 不可能,简单的python导入只会将模块添加到当前名称空间。

Now there are 3 alternatives for importing MyClass : 现在,有3种替代方法可用于导入MyClass

# mypkg/__init__.py
from submodule import MyClass
__all__ = ["MyClass"]

# mypkg/submodule.py
def MyClass(obj):
    pass

# test-usage.py
import mypkg
mypkg.MyClass()

# test-usage-2.py
from mypkg import MyClass
MyClass()

# test-usage-3.py
from mypkg import *
MyClass()

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

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