1. 程式人生 > >繼承和多態

繼承和多態

nbsp 被子 初始 core logs 定義 重寫 eight clas

類可以繼承自基類,也可以被子類繼承,比如Animal繼承自object類,而自身又可以被Dog和Cat類繼承

class Animal(object):
    def run(self):
        print(‘Animal is running‘)
class Dog(Animal):
  pass
class Cat(Animal):
  pass  

繼承的子類擁有了基類的全部屬性和方法,而且子類還可以在基類的基礎上新增屬性或者方法,如下代碼在printscore報錯

class Student(object):
    def __init__(self,name,score):
        self.__name=name
        self.__score=score
    
    def printscore(self):
        print(‘%s\‘s score is %s‘%(self.__name,self.__score))
        
class Junior(Student):
    def __init__(self,name,score,sex,height,weight):
        self.__name=name
        self.__score=score
        self.__sex=sex
        self.__height=height
        self.__weight=weight
    def printstudent(self):
        print(‘%s %s %s %s %s‘%(self.__name,self.__score,self.__sex,self.__height,self.__weight))
class Master(Student):
    pass

kimi=Junior(‘kimi‘,100,‘M‘,180,65)
kimi.printscore()
kimi.printstudent()

報錯的原因在於Junior重寫了初始化函數,因此Junior的實例中__name被更名為_Junior__name,而Student中的__name被更名為_Student__name,而printscore中調用的是_Student__name,導致調用失敗。通過本例理解了__打頭的變量就連自己的子類都無法調用。

上例正確的用法應該是  

class Student(object):
    def __init__(self,name,score):
        self.name=name
        self.score=score
    
    def printscore(self):
        print(‘%s\‘s score is %s‘%(self.name,self.score))
        
class Junior(Student):
    def __init__(self,name,score,sex,height,weight):
        self.name=name
        self.score=score
        self.sex=sex
        self.height=height
        self.weight=weight
    def printstudent(self):
        print(‘%s %s %s %s %s‘%(self.name,self.score,self.sex,self.height,self.weight))
class Master(Student):
    pass

kimi=Junior(‘kimi‘,100,‘M‘,180,65)
kimi.printscore()
kimi.printstudent()

還可以這麽定義Junior類:

class Junior(Student):
    def __init__(self,name,score,sex,height,weight):
        Student.__init__(self,name,score)#或者使用super(Junior,self).__init__(self,name,score)
        self.sex=sex
        self.height=height
        self.weight=weight
    def printstudent(self):
        print(‘%s %s %s %s %s‘%(self.name,self.score,self.sex,self.height,self.weight))

子類可以覆蓋基類的方法和屬性,如果一個函數的參數為基類,我們就可以傳入子類作為參數,因為子類屬於基類,而且函數並不因為傳入了子類而需要修改,對於一個變量,我們只需要知道它的基類,而具體的細節由它具體的子類來決定。允許新增子類,而不需要修改依賴該基類的函數。

  

  

繼承和多態