两种方式执行父类方法

class Base1(object):
    def func(self):
        print("Base1.func")

class Base2(object):
    def func(self):
        print("Base2.func")

class Foo(Base1, Base2):
    def func(self):
        # 方式一:根据mro的顺序执行方法
        super().func()  # Base1.func
        super(Foo,self).func()  # Base1.func
        # 方式二:主动执行Base类的方法
        Base2.func(self)  # Base2.func
        print("Foo.func")

obj = Foo()
obj.func()  # Foo.func

print(Foo.mro())  # [<class '__main__.Foo'>, <class '__main__.Base1'>, <class '__main__.Base2'>, <class 'object'>]

猜你喜欢

转载自www.cnblogs.com/believepd/p/10331515.html