Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Calling the __init__() method of a base class using super() when it requires arguments [duplicate]

I am trying to call the __init__() method in a superclass, where said method takes arguments, but it doesn't seem to be working. Please 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 have never been able to get this to work. What am I doing wrong? I would ideally like to use super() over A.__init__(self, <parameters>), if this is a possibility (which it must be).

like image 228
Lord Cat Avatar asked Jan 08 '23 10:01

Lord Cat


1 Answers

As a rule of thumb: in Python 2 your base class should always inherit from object, as otherwise you're using old style classes with surprising behaviors 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're doing (at least see the docs and this) and you want to use old-style classes you can't use super(), but instead need to manually call the super-class's __init__ from the sub class like this:

class A:
    ...

class B(A):
    def __init__(self, p1, p2, p3):
        A.__init__(p1, p2)
        ...
like image 52
Jörn Hees Avatar answered Jan 15 '23 04:01

Jörn Hees