0

I have the following code segment, which is shown as follows along with its output

from abc import ABCMeta, abstractmethod
  
class AbstractClass(object, metaclass=ABCMeta):
    @abstractmethod
    def __init__(self, n):
        self.n = n
        print('the salary information')
 
 
class Employee(AbstractClass):
    def __init__(self, salary, name):
        self.salary = salary
        self.name = name
        super(AbstractClass,self).__init__()
 
emp1 = Employee(1000000, "Tom")
print(emp1.salary)
print(emp1.name)

I would like to let the subclass, e.g. Employee, can also inherit the functionality implemented in the constructor of AbstractClass. In specific, the print('the salary information') I added:

super(AbstractClass,self).__init__()  # which does not work
martineau
  • 119,623
  • 25
  • 170
  • 301
user297850
  • 7,705
  • 17
  • 54
  • 76
  • Worth noting, by the way, that changing the signature of `__init__` in a subclass like this violates the Liskov Substitution Principle, so may not be advisable. Difficult to advise on a fix as it's not clear what the purpose of your `n` attribute is. https://en.wikipedia.org/wiki/Liskov_substitution_principle – Alex Waygood Aug 01 '21 at 23:33

1 Answers1

1

You need to pass the CURRENT class to super, not the parent. So:

        super(Employee,self).__init__()

Python will figure out which parent class to call.

When you do that, it won't work, because AbstractClass.__init__ requires an additional parameter that you aren't providing.

FOLLOWUP

It has been correctly pointed out that this will suffice:

        super().__init__(0)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Is there a reason not to just use the zero argument form here? `super().__init__('n')`? (or whatever `n` is in the super init)? – Mark Aug 01 '21 at 05:05
  • I'm not sure what you're asking. He needs to provide some argument to `super().__init__`. We don't know what the argument needs to be. I suspect this is all just a skeleton for the sake of the question anyway. – Tim Roberts Aug 01 '21 at 05:08
  • 2
    I'm asking if you really *need* to pass the CURRENT class to super. Why not just `super()` instead of `super(Employee,self)`. – Mark Aug 01 '21 at 05:09
  • 1
    Yes, you can. That was a change in Python 3.0 (before that, you DID have to specify the base class), and I use `super` so rarely I forget. Good point. – Tim Roberts Aug 01 '21 at 05:12