Python: calling base class __init __ () method with super () when it requires arguments
I am trying to call a method __init__()
on a superclass where said method takes arguments, but it doesn't seem to work. See the code below:
>>> class A:
def __init__(self, param1, param2):
self._var1 = param1
self._var2 = param2
>>> class B(A):
def __init__(self, param1, param2, param3):
super(B, self).__init__(param1, param2)
self._var3 = param3
>>> a = A("Hi", "Bob")
>>> a._var1
'Hi'
>>> a._var2
'Bob'
>>>
>>> b = B("Hello", "There", "Bob")
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
b = B("Hello", "There", "Bob")
File "<pyshell#69>", line 3, in __init__
super(B, self).__init__(param1, param2)
TypeError: must be type, not classobj
>>>
I could never get this to work. What am I doing wrong? Ideally I would like to use super()
over A.__init__(self, <parameters>)
if possible (which it should be).
source to share
As a rule of thumb: In Python 2, your base class must always inherit from object
, as otherwise you are using old-style classes with amazing behavior like the one you describe.
So try
class A(object):
...
like this:
In [1]: class A(object):
...: def __init__(self, param1, param2):
...: self._var1 = param1
...: self._var2 = param2
...:
In [2]: class B(A):
...: def __init__(self, param1, param2, param3):
...: super(B, self).__init__(param1, param2)
...: self._var3 = param3
...:
In [3]: a = A("Hi", "Bob")
In [4]: a._var1
Out[4]: 'Hi'
In [5]: a._var2
Out[5]: 'Bob'
In [6]: b = B("Hello", "There", "Bob")
In [7]: b._var3
Out[7]: 'Bob'
If you really know what you are doing (at least see the docs and this ) and you want to use old style classes, you cannot use super()
, but instead need to manually call the superclass class __init__
from the subclass like this:
class A:
...
class B(A):
def __init__(self, p1, p2, p3):
A.__init__(p1, p2)
...
source to share
You can still use old style classes, but in this case, the base class method __init__
must be explicitly specified:
class A:
def __init__(self, param1, param2):
self._var1 = param1
self._var2 = param2
class B(A):
def __init__(self, param1, param2, param3):
A.__init__(self, param1, param2)
self._var3 = param3
Test:
>>> b = B("Hello", "There", "Bob")
>>> b._var1
'Hello'
>>> b._var2
'There'
>>> b._var3
'Bob'
>>>
source to share