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'>)