python 類的繼承與過載

liying700發表於2017-06-14
>>> class human:
    __age=0
    __sex=''
    __height=0
    __weight=0
    name=''
    def __init__(self,age,sex,height,weight):
        self.__age=age
        self.__sex=sex
        self.__height=height
        self.__weight=weight
    def setname(self,name):
        self.name=name
    def show(self):
        print(self.name)
        print(self.__age)
        print(self.__sex)
        print(self.__height)
        print(self.__weight)


>>> class student(human):#通過繼承human類生成student類
    __classes=0
    __grade=0
    __num=0
    def __init__(self,classes,grade,num,age,sex,height,weight):#過載
        self.__classes=classes
        self.__grade=grade
        self.__num=num
        human.__init__(self,age,sex,height,weight)#呼叫human類的__init__方法,初始化huamn類的屬性,過載huamn類後又使用類的該方法,則用“父類.方法名”的方式呼叫
    def show(self):#過載show()方法
        human.show(self)#呼叫huamnn類的show方法
        print(self.__classes)
        print(self.__grade)
        print(self.__num)
>>> a=student(12,3,20070305,19,'male',175,65)#例項化生成a物件
>>> a.setname('tom')#呼叫setname方法
>>> a.show()#呼叫show方法,即用過載後的show方法輸出屬性
tom
19
male
175
65
12
3
20070305

相關文章