All is well 3 idiots

AC小小常

【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

 

posted on 2020-04-14 17:51  AC小小常  阅读(155)  评论(0编辑  收藏  举报

导航