python之继承

I. 继承

(1)父类没有,子类有的方法,叫拓展
(2)重写了父类的方法,调用自身方法
(3)子类没有,父类有的方法,继承父类方法


II.多继承
(1)可以继承多个父类
(2)应避免父类间存在继承关系
(3) 继承两个同名的父类方法,就近原则继承 : 即优先调用前面的方法

class RobotOne:  # 第一代机器人
    def __init__(self, year, name):
        self.year = year
        self.name = name

    def walking_on_flat_ground(self):
        print(self.name + "能在平地上行走")

    def robot_info(self):
        print("{0}年生产的机器人{1},是中国研发的".format(self.year, self.name))


class RobotTwo:  # 第二代机器人
    def __init__(self, name):
        self.name = name

    def walking_on_flat_ground(self):
        print(self.name + "可以在平地上平稳的行走")

    def walking_avoid_blick(self):
        print(self.name + "可以避开障碍物")


class RobotThree(RobotOne,RobotTwo): #第三代机器人,建议RobotOne与RobotTwo中间无继承关系

    # 重写方法
    def robot_info(self):
        print("{0}年生产的机器人{1},今年{2}岁了".format(self.year, self.name,2020 - int(self.year)))

    # 拓展方法
    def jump(self):
        print(self.name + "可以单膝跳跃")


robot3 = RobotThree('2000','大王')

robot3.jump()
print("===1.父类没有,子类有的方法,叫拓展==========")

robot3.robot_info()
print("===2.重写了父类的方法,打印自身方法==========")

robot3.walking_on_flat_ground()
print("===3.两个父类的同名方法,采取就近原则继承==========")

robot3.walking_avoid_blick()
print("===4.子类没有,父类有的方法,继承父类方法==========")

打印结果为:

III.超继承
(1)子类重写了父类的方法,然后又想调用父类里面的一些方法
(2)根据子类查找父类 : super(子类名,self关键字).方法名()
(3)超继承:父类名.方法名(self)或super().方法名()

注意: 只能继承共有方法,不能继承私有方法

class BasePhone:
    def call_phone(self):
        print("拨打语音通话")
        
class PhoneV1(BasePhone):
    def display_music(self):
        print("播放音乐")
    def send_msg(self):
        print("发短信")
    
class PhoneV2(PhoneV1):
    def call_phone(self):
        print("拨打视频电话") # 重写
        print("视频电话5分钟后,切换为语音电话")
        # 调用父类的同名方法
        BasePhone.call_phone(self) # 超继承1
        super().call_phone() # 超继承2
    def game(self): # 拓展
        print("打游戏")
    def send_msg(self): # 保留原来的方法,并进行拓展
        super().send_msg()# 继承
        print("发彩信") # 扩展
        
原文地址:https://www.cnblogs.com/kite123/p/12522421.html