python中有多少个类,我应该将多少个Python类放在一个文件中?

I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organising classes.

解决方案

A Python file is called a "module" and it's one way to organize your software so that it makes "sense". Another is a directory, called a "package".

A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be perfectly sensible to people who will read, maintain and extend your software.

The rule is this: a module is the unit of reuse.

You can't easily reuse a single class. You should be able to reuse a module without any difficulties. Everything in your library (and everything you download and add) is either a module or a package of modules.

For example, you're working on something that reads spreadsheets, does some calculations and loads the results into a database. What do you want your main program to look like?

from ssReader import Reader

from theCalcs import ACalc, AnotherCalc

from theDB import Loader

def main( sourceFileName ):

rdr= Reader( sourceFileName )

c1= ACalc( options )

c2= AnotherCalc( options )

ldr= Loader( parameters )

for myObj in rdr.readAll():

c1.thisOp( myObj )

c2.thatOp( myObj )

ldr.laod( myObj )

Think of the import as the way to organize your code in concepts or chunks. Exactly how many classes are in each import doesn't matter. What matters is the overall organization that you're portraying with your import statements.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值