【Python面向对象】(2)继承

时间:2020-04-14
本文章向大家介绍【Python面向对象】(2)继承,主要包括【Python面向对象】(2)继承使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

子类可以选择直接继承父类的方法,也可以重写父类方法

调用父类方法:super(子类名,self).父类方法

子类判断:issubclass(子类名, 父类名)

class BaseCat(object):
    """
    猫科动物的基础类
    """
    tag = "猫科动物"

    def __init__(self, name):
        self.name = name  # 猫都有名字

    def eat(self):
        """猫吃东西"""
        print("猫都吃东西")
class Tiger(BaseCat):
    """
    老虎类
    """
    def eat(self):
        # 调用父类方法
        super(Tiger, self).eat()
        print("我喜欢吃肉")
class Panda(BaseCat):
    """
    熊猫类
    """
    pass


class PetCat(BaseCat):
    """
    家猫类
    """
    def eat(self):
        # 调用父类方法
        super(PetCat, self).eat()
        print("我喜欢吃猫粮")


class HuaCat(PetCat):
    """
    中华田园猫
    """
    def eat(self):
        # 调用父类方法
        super(HuaCat, self).eat()
        print("我喜欢吃零食")


class DuanCat(PetCat):
    """
    英国短毛
    """
    def eat(self):
        print("我啥都吃")


if __name__ == "__main__":
    # 实例化中华田园猫
    cat = HuaCat('小黄')
    cat.eat()
    # 输出:
    # 猫都吃东西
    # 我喜欢吃猫粮
    # 我喜欢吃零食
    print("-----------------")
    # 重写父类方法
    cat_d = DuanCat('小灰')
    cat_d.eat()  # 输出:我啥都吃
    print("-----------------")
    # 直接继承父类方法
    panda = Panda('圆圆')
    panda.eat()  # 输出:猫都吃东西

    # 子类的判断
    print(issubclass(DuanCat, BaseCat))  # 输出:True
    print(issubclass(DuanCat, PetCat))  # 输出:True
    print(issubclass(DuanCat, Tiger))  # 输出:False

原文地址:https://www.cnblogs.com/ac-chang/p/12699610.html