python 继承

124 阅读1分钟

所有类的顶级类 object

所有子类默认继承父类的所有属性和方法

class A():
    def __init__(self):
        self.num = 1

    def info_ptint(self):
        print(self.num)

class B(A):
    pass

result = B()
result.info_ptint() #1

当一个类有多个父类的时候,默认使用第一个父类的同名属性和方法

class Master():
    def __init__(self):
        self.kongfu = '[古法制作]'

    def info_ptint(self):
        print(f'运用{self.kongfu}')

    def secret(self):
        print('秘制手法')

class School():
    def __init__(self):
        self.kongfu = '[新式制作]'

    def info_ptint(self):
        print(f'运用{self.kongfu}')

class Prentice(School, Master):
    pass

student = Prentice()
student.info_ptint()    #运用[新式制作]
student.secret()        #秘制手法

子类重写

class Master():
    def __init__(self):
        self.kongfu = '[古法制作]'

    def info_ptint(self):
        print(f'运用{self.kongfu}')

    def secret(self):
        print('秘制手法')

class School():
    def __init__(self):
        self.kongfu = '[新式制作]'

    def info_ptint(self):
        print(f'运用{self.kongfu}')

class Prentice(School, Master):
    def __init__(self):
        self.kongfu = '[独门制作]'

student = Prentice()
student.info_ptint()    #运用[独门制作]

魔法方法 .__ mro __ 快速查看继承关系

class Master():
    def __init__(self):
        self.kongfu = '[古法制作]'

    def info_ptint(self):
        print(f'运用{self.kongfu}')

    def secret(self):
        print('秘制手法')


class Prentice(Master):
    def __init__(self):
        self.kongfu = '[独门制作]'

student = Prentice()
student.info_ptint()    #运用[独门制作]

print(Prentice.__mro__)


# class '__main__.Prentice'>, < class '__main__.Master' >, < class 'object' > ) 'object'>)

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

class Master():
    def __init__(self):
        self.kongfu = '[古法制作]'

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

    def secret(self):
        print('秘制手法')

class School():
    def __init__(self):
        self.kongfu = '[新式制作]'

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



class Prentice(School, Master):
    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)

student = Prentice()
student.make_cake()            #运用[独门制作]
student.make_master_cake()     #运用[古法制作]

super() 父类 super().函数()

私有属性或方法 在名字前加 _ _ 两个下划线就行 只能在类里面进行修改私有属性,一般用get_xxx() set_xxx()