Can I put a class definition into __init__.py?

后端 未结 1 675
刺人心
刺人心 2021-01-02 06:08

I have a package with a class structure similar to this. Base class is a typical, simple parent class for a few separate hierarchies.

My package layout

相关标签:
1条回答
  • 2021-01-02 06:39

    It is perfectly fine and a more flexible approach to leave it in base.py. Also note that the primary use of __init__.py is to initialize Python packages and not to hold content.

    To avoid having to import the module each time you can write something like

    # in __init__.py
    from .base import Base
    

    into the __init__.py such that you can directly import Base from my_package:

    # some script
    from my_package import Base
    

    This is a common approach to make objects available at the package level.

    For more info about the __init__.py file check out the documentation.

    0 讨论(0)
提交回复
热议问题