Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

python - Can I put a class definition into __init__.py?

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 looks like this:

__init__.py (empty)
base.py
ab.py
cd.py
ef.py

Is it a good idea or good practice to put Base class into __init__.py instead of creating separate module just for one class? In this way I wouldn't need to import it each time in modules.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...