tags:

views:

138

answers:

2

I'm trying to overwrite a __init__ method, but when I call the super method the attributes created in that method are not available. I can see that it's not an inheritance problem since class B still has the attributes available.

I think the code sample will explain it better :-)

Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
...   def __init__(self, *args, **kwargs):
...     self.args = args
...     self.kwargs = kwargs
... 
>>> a = A('a', 'b', key='value')
>>> print a.args, a.kwargs
('a', 'b') {'key': 'value'}
>>> class B(A):
...   pass
... 
>>> b = B('b', 'c', key_b='value_b')
>>> print b.args, b.kwargs
('b', 'c') {'key_b': 'value_b'}
>>> class C(A):
...   def __init__(self, *args, **kwargs):
...     print 'class C'
...     super(A, self).__init__(*args, **kwargs)
... 
>>> c = C('c', 'd', key_c='value_C')
class C
>>> print c.args, c.kwargs
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'args'
>>> class D(A):
...   def __init__(self, *args, **kwargs):
...     super(A, self).__init__(*args, **kwargs)
...     print 'D'
... 
>>> d = D('d', 'e', key_d='value D')
D
>>> print d.args, d.kwargs
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'args'
>>>
+5  A: 

Your call to the superclass needs to use its own type

super(D, self).__init__(*args,**kwargs)

rather than

super(A...

I believe calling super(A, self).__init__ will call the superclass of A, which is object. Rather, you want to call the superclass of D, which is A.

Smashery
+3  A: 

You're using super() incorrectly. In your "C" class the second line of the init() method should pass C as the first argument like so...

super(C, self).__init__(*args, **kwargs)

And really you shouldn't even need to use super here. You could just call

A.__init__(self, *args, **kwargs)
Trey Stout