Python入门的36个例子 之 32 -> OOP – Inheritance 继承

 

源代码下载:下载地址在这里

 

A Byte Of Python 中关于继承有这样的文字:

 

Suppose you want to write a program which has to keep track of the teachers and students in a college. They have some common characteristics such as name, age and address. They also have specific characteristics such as salary, courses and leaves for teachers and, marks and fees for students.
You can create two independent classes for each type and process them but adding a new common characteristic would mean adding to both of these independent classes. This quickly becomes unwieldy.
A better way would be to create a common class called SchoolMember and then have the teacher and student classes inherit from this class i.e. they will become sub-types of this type (class) and then we can add specific characteristics to these sub-types.

 

 

这段文字很简单,我开始也这么认为。但当我不小心第二次读这本书的时候才领会到这些文字所要传达的深意。

继承在我看来,或者说在以前的我看来,是为了代码重用,是的,我现在也这么认为。但,对于为什么继承有利于代码重用我却有了不同的理解。以前的理解 是这样的:我先写一个类,以后需要扩展这个类的功能的时候就先继承它,然后再添加一些方法等。这样就算是代码重用了。现在我有了新的理解:继承的本质是将共性和个性分离。 在设计类的一开始,我们甚至已经明白了这个类在以后的用处以及会被如何地继承,我们将共性和个性分开,是我们对整个系统的修改变得简单。说的更明白一点,与其说“继承机制”是为了代码重用,不如说是为了代码维护。在计算机世界,无数事实告诉我们,分离的东西是好的。

 

 

output:

 

初始化灭绝师太
初始化老师: 灭绝师太
初始化韩美眉
初始化学生:韩美眉

名字:灭绝师太 年龄:60
薪水:30000
名字:韩美眉 年龄:21
分数:99

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章