python - Assuming `obj` has type `objtype`, are `super(cls,obj)` and `super(cls,objtype)` the same? -
in python, assuming obj
has type objtype
, super(cls,obj)
, super(cls,objtype)
same?
is correct super(cls,obj)
converts obj
object class superclass of objtype
after cls
in mro of objtype
?
what super(cls,objtype)
mean then?
for example, given implementation of 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 not further override __new__
) has 1 instance.
what super(singleton, cls)
mean, cls
class? return?
thanks.
according docs, super
return proxy object delegates method calls parent or sibling class of type.
so super
returns object knows how call methods of other classes in class hierarchy.
the second argument super
object super
bound; instance of class, if super
being called in context of method classmethod or staticmethod want call method on class object rather instance.
so calling super(someclass, cls).some_method()
means call some_method
on classes someclass
descends from, rather on instances of these classes. otherwise super
calls behave super
call in instance method.
the usage looks more natural in less complicated code:
class c(somebaseclass): def method(self): # bind super 'self' super(c, self).method() @classmethod def cmethod(cls): # no 'self' here -- bind cls super(c, cls).cmethod()
note super(c, cls)
required in python2, empty super()
enough in python3.
in singleton example, super(singleton, cls).__new__(cls)
returns result of calling object.__new__(cls)
, instance of singleton
. it's being created way avoid recursively calling singleton.__new__
.
Comments
Post a Comment