Discuss / Python / 多重继承查找优先级

多重继承查找优先级

Topic source

よろしく

#1 Created at ... [Delete] [Delete and Lock User]

# -*- coding: utf-8 -*-

class Animal(object):

    def run(self):

        print("Animal run")

class Dog(Animal):

    def run(self):

        print("Dog run")

class Cat(Animal):

    def run(self):

        print("Cat run")

class Dc(Dog,Cat):#继承列表有先后顺序

    def run1(self):

        self.run() #继承自Dog的run方法

    def run2(self):

        super().run()#super()指向了优先级最高的Dog的run方法

    def run3(self):

        Cat.run(self)#通过类名直接调用,已脱离继承的范畴

    def run4(self):#整活性质

        super(Dog, self).run()#表示在继承链中查找Dog下一个类的run()方法,也就是Cat

        super(Cat, self).run()#同上,Cat后是Animal

dc1 = Dc()

dc1.run() #Dog run

dc1.run1() #Dog run

dc1.run2() #Dog run

dc1.run3() #Cat run

dc1.run4() #Cat run\n Animal run

#得出继承查找顺序:Dc>Dog>Cat>Animal


  • 1

Reply