Second argument to super().

Steven Bethard steven.bethard at gmail.com
Wed Mar 9 15:35:03 EST 2005


Tobiah wrote:
> What is the purpose of the second argument to super()?

You probably want to check the docs[1] again.  They give an example:

class C(B):
     def meth(self, arg):
         super(C, self).meth(arg)

> What is meant by the returning of an 'unbound' object
> when the argument is omitted.

If you supply a second argument (an instance of the type) to super, the 
returned object will be bound to that instance.  For example:

py> class C(object):
...     def g(self):
...         print 'g'
...
py> class D(C):
...     def h(self):
...         print 'h'
...
py> d = D()
py> s = super(D, d)
py> d2 = D()
py> s2 = super(D, d2)
py> s == s2
False

Note that the object returned depends on the instance passed in.  An 
'unbound' object would not be bound in this way to the instance.

Note also that the super object returned has access only to the methods 
of the superclass:

py> s.g
<bound method D.g of <__main__.D object at 0x01186130>>
py> d.g
<bound method D.g of <__main__.D object at 0x01186130>>
py> s.h
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'super' object has no attribute 'h'
py> d.h
<bound method D.h of <__main__.D object at 0x01186130>>


> Also, when would I pass an object as the second argument,
> and when would I pass a type?

For most use cases, you'll probably only want an object (an instance). 
You might run into the type case if you define the staticmethod __new__ 
in a class:

py> class S(str):
...     def __new__(cls, s):
...         return super(S, cls).__new__(cls, 'S(%s)' %s)
...
py> S('abc')
'S(abc)'

In this case __new__ takes as a first argument the class (type) of the 
object, so if you want to invoke the superclass __new__, you need to 
pass the type to super.  (You don't have an instance to pass.)


STeVe

[1] http://docs.python.org/lib/built-in-funcs.html#l2h-70



More information about the Python-list mailing list