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

 

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