why and how to use Python's super(type1, type2)?

会有一股神秘感。 提交于 2019-12-05 15:43:13
outis

You pass an object if you want to invoke an instance method. You pass a class if you want to invoke a class method.

The classic example for using super() for class methods is with factory methods, where you want all the superclass factory methods to be called.

class Base(object):
    @classmethod
    def make(cls, *args, **kwargs):
        print("Base.make(%s, %s) start" % (args, kwargs))
        print("Base.make end")

class Foo(Base):
    @classmethod
    def make(cls, *args, **kwargs):
        print("Foo.make(%s, %s) start" % (args, kwargs))
        super(Foo, cls).make(*args, **kwargs)
        print("Foo.make end")

class Bar(Base):
    @classmethod
    def make(cls, *args, **kwargs):
        print("Bar.make(%s, %s) start" % (args, kwargs))
        super(Bar, cls).make(*args, **kwargs)
        print("Bar.make end")

class FooBar(Foo,Bar):
    @classmethod
    def make(cls, *args, **kwargs):
        print("FooBar.make(%s, %s) start" % (args, kwargs))
        super(FooBar, cls).make(*args, **kwargs)
        print("FooBar.make end")

fb = FooBar.make(1, 2, c=3)

"Invoking a superclass's class methods in Python" has a real-world example.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!