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

眉间皱痕 提交于 2019-12-07 08:39:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7466463/why-and-how-to-use-pythons-supertype1-type2

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