Alcott
Alcott

Reputation: 18585

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

super has 2 args,

super(type, obj_of_type-or-subclass_of_type)

I understand how and why to use super with the 2nd arg being obj_of_type. But I don't understand the matter for the 2nd arg being subclass.

Anyone can show why and how?

Upvotes: 5

Views: 817

Answers (1)

outis
outis

Reputation: 77400

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.

Upvotes: 3

Related Questions