python中关于包的定义,Python:在包中定义类

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 package is to define them in __init__.py of that package. Coming from Java, I'd kind of like to define individual files for my classes. Is this a recommended practice?

I'd like to have my directory look somewhat like this:

recursor/

__init__.py

RecursionException.py

RecursionResult.py

Recursor.py

So I could refer to my classes as "recursor.Recursor," "recursor.RecursionException," and "recursor.RecursionResult". Is this doable or recommended in Python?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值