Define Classes in Packages

纵然是瞬间 提交于 2019-12-04 01:40:41

Go ahead and define your classes in separate modules. Then make __init__.py do something like this:

from RecursionException import RecursionException
from RecursionResult import RecursionResult
from Recursor import Recursor

That will import each class into the package's root namespace, so calling code can refer to recursor.Recursor instead of recursor.Recursor.Recursor.

I feel the need to echo some of the other comments here, though: Python is not Java. Rather than creating a new module for every class under the sun, I suggest grouping closely related classes into a single module. It's easier to understand your code that way, and calling code won't need a bazillion imports.

This is perfectly doable. Just create a new class module for each of those classes, and create exactly the structure you posted.

You can also make a Recursion.py module or something similar, and include all 3 classes in that file.

(I'm also new to Python from Java, and I haven't yet put anything in my __init__.py files...)

In Python you're not restricted to defining 1 class per file and few do that. You can if you want to though - it's totally up to you. A Package in Python is just a directory with an

__init__.py 

file. You don't have to put anything in that file you can to control what gets imported etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!