python-20 继承

所有类的顶级类 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值