經典類與新式類的繼承順序
阿新 • • 發佈:2018-05-07
wan search private int super study pytho alice 深度
1 #經典類與新式類的繼承順序 2 3 class Teacher(object): 4 cn=‘Harvard‘ 5 def __init__(self,name,age,sex): 6 self.name=name 7 self.age=age 8 self.sex=sex 9 self.__money=5600 10 11 def show_private_attribule(self): 12 print(‘private attribute:%s‘ %self.__money) 13 14 class Master(Teacher): 15 def __init__(self,name,age,sex,subject): 16 Teacher.__init__(self,name,age,sex)#重構父類的構造函數,繼承多個就多寫一個 17 #super(Master,self).__init__(name,age,sex) #通用寫法,繼承多個父類都可以用這一個 18 #繼承多個類,只運行第一個類的構造函數,其它的不運行 19#沒有,橫向逐個找,向上找(查找策略:廣度優先 )(新式類) 20 #python2.x是深度優先 (經典類) 21 self.subject=subject 22 print(‘in the Master‘) 23 24 def speak(self): 25 print(‘I am master %s I study %s subject‘ %(self.name,self.subject))26 27 class Doctor(Teacher): 28 def __init__(self,name,age,sex,allowance): 29 Teacher.__init__(self, name, age, sex) 30 #super(Doctor,self).__init__(name,age,sex) 31 self.allowance=allowance 32 print(‘in the Doctor‘) 33 34 def ralation(self,obj): 35 print(‘%s is %s \‘s student‘ %(obj.name,self.name)) 36 37 class Specialist(Master,Doctor): 38 def __init__(self,name,age,sex,subject,allowance,research_field):#先查找Master構造執行,沒有向Doctor查找,再沒有向上Teacher查找 39 Master.__init__(self,name,age,sex,subject) 40 Doctor.__init__(self,name,age,sex,allowance) 41 self.research_field=research_field 42 print(‘in the Specialist‘) 43 44 t1=Teacher(‘Jack‘,26,‘M‘) 45 m1=Master(‘Alice‘,22,‘F‘,‘French‘) 46 d1=Doctor(‘Monica‘,28,‘F‘,6600) 47 s1=Specialist(‘Jones‘,32,‘F‘,‘French‘,6600,‘language‘)
經典類與新式類的繼承順序