使用代码模拟实物时,你可能会发现自己给类添加的细节越来越多:属性和方法清单以及文件都越来越长。在这种情况下,可能需要将类的一部分作为一个独立的类提取出来。你可以将大型类拆分成多个协同工作的小类。
这里把 狗狗类做了一个封装。全部狗狗信息放到doginfo里呢。调用时:实例.属性(相当于类).属性下的属性或方法。见14和16行。




这看似做了很多额外的工作,但现在我们想多详细地描述电瓶都可以,且不会导致ElectricCar 类混乱不堪。下面再给Battery 类添加一个方法,它根据电瓶容量报告汽车 的续航里程:


新增的方法get_range() 做了一些简单的分析:如果电瓶的容量为70kWh,它就将续航里程设置为240英里;如果容量为85kWh,就将续航里程设置为270英里,然后报告 这个值。为使用这个方法,我们也通过汽车的属性battery 来调用它。
网友评论