Define Classes in Packages

后端 未结 3 1585
醉酒成梦
醉酒成梦 2021-02-20 02:57

I\'m learning Python and I have been playing around with packages. I wanted to know the best way to define classes in packages. It seems that the only way to define classes in a

3条回答
  •  情书的邮戳
    2021-02-20 03:43

    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.

提交回复
热议问题