Reputation: 99488
In Python, assuming that obj
has type objtype
, are super(cls,obj)
and super(cls,objtype)
the same?
Is it correct that super(cls,obj)
converts obj
to another object whose class is a superclass of objtype
which is after cls
in the MRO of objtype
?
What does super(cls,objtype)
mean then?
For example, given an implementation of the Singleton design pattern:
class Singleton(object):
_singletons = {}
def __new__(cls, *args, **kwds):
if cls not in cls._singletons:
cls._singletons[cls] = super(Singleton, cls).__new__(cls)
return cls._singletons[cls]
any subclass of Singleton
(that does not further override __new__
) has exactly one instance.
What does super(Singleton, cls)
mean, where cls
is a class? What does it return?
Thanks.
Upvotes: 1
Views: 60
Reputation: 55824
According to the docs, super
Return a proxy object that delegates method calls to a parent or sibling class of type.
So super
returns an object which knows how to call the methods of other classes in the class hierarchy.
The second argument to super
is the object to which super
is bound; generally this is an instance of the class, but if super
is being called in the context of a method that is a classmethod or staticmethod then we want to call the method on the class object itself rather than an instance.
So calling super(SomeClass, cls).some_method()
means call some_method
on the classes that SomeClass
descends from, rather than on instances of these classes. Otherwise super
calls behave just like a super
call in an instance method.
The usage looks more natural in less complicated code:
class C(SomeBaseClass):
def method(self):
# bind super to 'self'
super(C, self).method()
@classmethod
def cmethod(cls):
# no 'self' here -- bind to cls
super(C, cls).cmethod()
Note that super(C, cls)
is required in python2, but an empty super()
is enough in python3.
In your singleton example, super(Singleton, cls).__new__(cls)
returns the result of calling object.__new__(cls)
, an instance of Singleton
. It's being created this way to avoid recursively calling Singleton.__new__
.
Upvotes: 1