Python课程第十三天_下午_课程笔记(继承)

Day_13_PM_Inherit

# 继承

# object: 根类,超类

# 单继承: 只有一个父类
# 多继承: 有多个父类

# 父类: 基类
class Ipad(object):
    def __init__(self, price):
        self.price = price

    def movie(self):
        print('看电影')

# 子类: 派生类
class Iphone(Ipad):
    def __init__(self, price, color):
        # 需要调用父类的init方法: 对父类属性进行初始化
        # Ipad.__init__(self, price)  #显式调用
        super().__init__(price)  # 隐式调用, 自动指向父类

        self.__color = color


# 子类
class Iwatch(Iphone):
    def __init__(self, price, color, size):
        super().__init__(price, color)
        self.size = size

    def health(self):
        print(self.price)
        # print(self.__color)  # 不能使用父类的私有属性和私有方法, 私有属性和私有方法不能继承

# 对象
# iphone = Iphone(1000, 'green')
# print(iphone.price, iphone.color)
# iphone.movie()

# iwatch = Iwatch(2000, 'yellow', '1.8')
# print(iwatch.price, iwatch.size)
# iwatch.movie()
# iwatch.health()


# 多继承
# 父类
class Father:
    def __init__(self, name):
        self.name = name

    def run(self):
        print('会跑步')


# 父类
class Mother:
    def __init__(self, age):
        self.age = age

    def cook(self):
        print('会做饭')


# 子类
class Son(Father, Mother):
    def __init__(self, name, age, height):
        # 显式调用
        # Father.__init__(self, name)
        # Mother.__init__(self, age)

        # 隐式调用
        # super().__init__(name)
        super(Son, self).__init__(name)  # 继承Father
        super(Father, self).__init__(age)  # 继承Mother
        self.height = height


# 对象
son = Son('哪吒', 8, 1)
print(son.name, son.age, son.height)
son.run()
son.cook()


# mro算法: 从左往右的继承链
print(Son.__mro__)
# (<class '__main__.Son'>,
# <class '__main__.Father'>,
# <class '__main__.Mother'>,
# <class 'object'>)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值