Python类的继承

单继承

# Master继承Object
class Master(object):
    # __init__是个魔法方法,用于初始化
    def __init__(self):
        self.kongfu = '师父功夫'
    def print_info(self):
        print(f'{self.kongfu}')
# dizi继承Master,默认继承父类一般的属性和方法
class dizi(Master):
    pass

di = dizi()
di.print_info()

多继承

class Master(object):
    def __init__(self):
        self.kongfu = '师父功夫'

    def make_cake(self):
        print(f'{self.kongfu}')

class School(object):
    def __init__(self):
        self.kongfu = '校园功夫'

    def make_cake(self):
        print(f'{self.kongfu}')
# 继承Master和School,子类没有自己的属性和方法时默认使用第一个父类的同名方法和属性
class Prentice(Master,School):
    pass

di = Prentice()
di.make_cake()

子类覆盖

class Master(object):
    def __init__(self):
        self.kongfu = '师父'

    def make_cake(self):
        print(f'{self.kongfu}')

class School(object):
    def __init__(self):
        self.kongfu = '学校'

    def make_cake(self):
        print(f'{self.kongfu}')

class Prentice(Master,School):
    def __init__(self):
        self.kongfu = '独创'

    def make_cake(self):
        print(f'{self.kongfu}')

di = Prentice()
di.make_cake()

子类调用父类的同名方法和属性

class Master(object):
    def __init__(self):
        self.kongfu = '古法'

    def make_cake(self):
        print(f'{self.kongfu}')

class School(object):
    def __init__(self):
        self.kongfu = '白马'

    def make_cake(self):
        print(f'{self.kongfu}')

class Prentice(Master,School):
    def __init__(self):
        self.kongfu = '独创'

    def make_cake(self):
        self.__init__()
        print(f'{self.kongfu}')

    def make_master_cake(self):
        # 方法中不进行初始化,原属性会被父类属性覆盖,调用父类方法不进行初始化,会使用子类的属性
        Master.__init__(self)
        Master.make_cake(self)

    def make_school_cake(self):
        School.__init__(self)
        School.make_cake(self)

chris = Prentice()
chris.make_master_cake()
chris.make_school_cake()
chris.make_cake()

查找类的继承关系可以用过魔法方法__mro__,例如:print(Prentice.mro)

posted @ 2021-03-09 10:33  code-G  阅读(84)  评论(0编辑  收藏  举报