【Python面向对象】(3)多重继承

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

注意:若同时继承的父类中有重名的方法,那么只会调用第一个,后面一个就不会调用了,所以在设计的时候,需要避免出现这样的错误

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

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

    def eat(self):
        """猫吃东西"""
        print("猫都吃东西")


class Protected(object):
    """
    受保护的类
    """
    def protect(self):
        print("我是受保护的")


class CountryProtected(object):
    """
    受国家级保护
    """
    def protect(self):
        print("我受国家级保护")


class Tiger(BaseCat, Protected):
    """
    老虎类
    """
    def eat(self):
        # 调用父类方法
        super(Tiger, self).eat()
        print("我喜欢吃肉")

    def protect(self):
        print("我是省级保护动物")

class Panda(BaseCat, Protected, CountryProtected): """ 熊猫类 """ pass

if __name__ == "__main__": panda = Panda("团团") panda.eat() # 输出:猫都吃东西 # Panda继承两个类,两个类中有同名的方法,调用了第一个后,第二个便不调用了 panda.protect() # 输出:我是受保护的 print("-----------------") tiger = Tiger("东北虎") tiger.eat() # 输出:猫都吃东西\n我喜欢吃肉 tiger.protect() # 输出:我是省级保护动物 # 子类判断 print(issubclass(Tiger, Protected)) # 输出:True print(issubclass(Tiger, BaseCat)) # 输出:True

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