(Python)继承
生活随笔
收集整理的這篇文章主要介紹了
(Python)继承
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
面向?qū)ο蟮牧硪粋€特性是繼承,繼承可以更好的代碼重用。
例如一個學(xué)校里面的成員有老師、學(xué)生。老師和學(xué)生都有共同的屬性名字和年紀(jì)。但老師還有它自己的屬性,如工資。學(xué)生也有它的屬性,如成績。
因此我們可以設(shè)計一個父類:SchoolPeople,兩個子類:Teacher、Student。
代碼如下:
SchoolPeople父類:
class SchoolPeople():
def __init__(self,name,age):
print "Init ShoolPeople"
self.name=name
self.age=age
def tell(self):
print "name is %s,age is %s" %(self.name,self.age)
Teacher子類:重寫了父類的tell方法。
class Teacher(SchoolPeople):
def __init__(self,name,age,salary):
SchoolPeople.__init__(self,name,age)
self.salary=salary
print "Init teacher"
def tell(self):
print "salary is %d" %self.salary
SchoolPeople.tell(self)
Student子類:沒有重寫父類的方法
class Student(SchoolPeople):
pass
調(diào)用:
t=Teacher("t1",35,10000)
t.tell()
print "\n"
s=Student("s1",10,95)
s.tell()
結(jié)果:
Init ShoolPeople
Init teacher
salary is 10000
name is t1,age is 35
Init ShoolPeople
name is s1,age is 10
結(jié)果分析:雖然子類Student子類沒有具體的實現(xiàn)代碼,默認(rèn)會調(diào)用父類的初始化函數(shù)和tell方法。
子類Teacher重寫了父類的tell方法,所以,他的實例會運行Techer類的tell方法。
總結(jié)
以上是生活随笔為你收集整理的(Python)继承的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: The 12 Months of the
- 下一篇: 4.n的高精度阶乘---优化