繼承應用、繼承與派生、supper
阿新 • • 發佈:2021-01-12
1.繼承應用
例子1
(1)原始程式碼
class student: def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender def choose(self): print('%s選課成功'%self.name) stu1=student('egon',18,'male') stu2=student('lxx',38,'male') stu3=student('lili',20,'female') classteacher: school='虹橋校區' def __init__(self,name,age,gender,level): self.name=name self.age=age self.gender=gender self.level=level def score(self): print('%s正在為學生打分'%self.name) teacher1=teacher('egon',18,'male',10) teacher2=teacher('lxx',38,'male',3)
(2)繼承和派生後
class people: <父類> school = '虹橋校區' def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender
class student(people): <子類+繼承> def choose(self):print('%s選課成功'%self.name) stu1=student('egon',18,'male') stu2=student('lxx',38,'male') stu3=student('lili',20,'female') class teacher(people): <子類+派生>
def __init__(self,name,age,gender,level):
people.__init__(self,name,age,gender) #呼叫函式
或 super.__init__(self,name,age,gender,level) #supper
(supper()返回的是一個特殊的物件,該物件會參考發起屬性查詢那個類的MRO列表,然後繼續往後找)
self.level=level def score(self):
print('%s正在為學生打分'%self.name)
teacher1=teacher('egon',18,'male',10)
teacher2=teacher('lxx',38,'male',3)
print(stu1.name)
print(teacher1.__dict__)
2.繼承實現的原理
如果繼承關係為非菱形結構,則會按照先找B這一條分支,然後再找C這一條分支,最後找D這一條分支的順序直到找到我們想要的屬性
如果繼承關係為菱形結構,那麼屬性的查詢方式有兩種,分別是:深度優先和廣度優先
3.supper
supper()返回的是一個特殊的物件,該物件會參考發起屬性查詢那個類的MRO列表,然後繼續往後找
class a: def test(self): print('from a') super().test() class b: def test(self): print('from b') class c(a,b): pass obj=c() obj.test()
結果是:
from a
from b
4.多繼承的程式碼規範(mixins機制)
繼承表達是一個is-a的關係
class Vehicle: #都是交通工具 pass class FlyableMixin #都有飛行能力 def fly(self): print('flying') class CivilAircraft(FlyableMixin,Vehicle): pass class Helicopter(FlyableMixin,Vehicle): pass class Car(Vehicle): pass
5.組合
class people: school='上海校區' def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender class student(people): def choose(self): print('%s選課功能'%self.name) class teacher(people): def __init__(self,name,age,gender,level): people.__init__(self,name,age,gender) self.level=level def score(self): print('%s正在為學生打分'%self.name) class couse: def __init__(self,name,price,period): self.name=name self.price=price self.period=period def tell(self): print('課程資訊<%s:%s:%s>'%(self.name,self.price,self.period)) python=couse('python全棧開發',19980,'6m') linux=couse('linux',19000,'5m') stu1=student('egon',18,'male') stu2=student('tom',20,'female') tea1=teacher('egon',22,'male',10) tea2=teacher('lili',20,'male',3) stu1.couse=python #所謂的組合就是指這裡的組合使用的 stu1.couse.tell() #結果是:課程資訊<python全棧開發:19980:6m>