python基础-类的继承

 

继承:承创建的新类称为“子类”或“派生类”,被继承的类称为“基类”、“父类.

    继承的过程,就是从一般到特殊的过程.要实现继承,可以通过“继承”(Inheritance)和“组合”(Composition)来实现

    继承概念的实现方式主要有2类:实现继承、接口继承.

    实现继承是指使用基类的属性和方法而无需额外编码的能力

    接口继承是指仅使用属性和方法的名称、但是子类必须提供实现的能力(子类重构爹类方法)

 

组合方式实现多继承

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

class School(object):
    def __init__(self,name):
        self.name=name

    def sayhi(self):
        print("school name",self.name)

class SchoolMember(object):

    menber=0 #公有属性
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
        self.enrool() #每个子类都运行

    def enrool(self):
        print('%s has enroll' %self.name)
        SchoolMember.menber+=1 #累计增加,不能写this.menber+=menber这样写只会在子类调用的时候加1,没有传到父类

    def tell(self): #打印所有用户信息,实现如下
        print("-----info %s-----" %self.name)
        for v,k in self.__dict__.items(): #返回子类的 所有成员属性的字典
            print("%s:\t%s" %(v,k))

    def __del__(self):
        print("%s has del" %self.name)
        SchoolMember.menber-=1

class Teacher(SchoolMember):

    def __init__(self,name,age,sex,salary,course,school):
        #SchoolMember.__init__(self,name,age,sex) #经典类写法==SchoolMember.__init__(self,name,age,sex)
        super(Teacher,self).__init__(name,age,sex ) #新类式类写法
        self.salary=salary
        self.course=course
        self.school=school #组合继承,实现多继承

    def teach(self):
        print("school:%s teacher course %s" %(self.school.name,self.course))


class Student(SchoolMember):

    def __init__(self,name,age,sex,tuition,course):
        SchoolMember.__init__(self,name,age,sex)
        self.tuition=tuition
        self.course=course

    def pay_tuition(self):
        print("the student pay ",self.tuition)

school=School("南京大学")
t=Teacher("shi",23,"F",15000,"python",school) #组合继承,实现多继承
s=Student("san",26,'M',3000,"python")
t.teach()

"""
shi has enroll
san has enroll
school:南京大学 teacher course python
shi has del
san has del

"""

 多继承

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'
class A(object):
    def request(self):
        print('A.request')
    def finish(self):
        print('A.finish')
class C(A):
    def request(self):
        self.process()
        print('C.request')
    def finish(self):
        print('C.finish')
class B(object):
    def request(self):
        print('B.request')
    def process(self):
        print('B.process')
        self.finish()
    def finish(self):
        print('B.finish')
class D(C, B):
    pass
obj = D()
obj.request()

"""
B.process
C.finish
C.request
"""

posted on 2017-05-30 14:58  shisanjun  阅读(199)  评论(0编辑  收藏  举报

导航