I have the following code segment, which is shown as follows along with its output
JavaScript
x
19
19
1
from abc import ABCMeta, abstractmethod
2
3
class AbstractClass(object, metaclass=ABCMeta):
4
@abstractmethod
5
def __init__(self, n):
6
self.n = n
7
print('the salary information')
8
9
10
class Employee(AbstractClass):
11
def __init__(self, salary, name):
12
self.salary = salary
13
self.name = name
14
super(AbstractClass,self).__init__()
15
16
emp1 = Employee(1000000, "Tom")
17
print(emp1.salary)
18
print(emp1.name)
19
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:
JavaScript
1
2
1
super(AbstractClass,self).__init__() # which does not work
2
Advertisement
Answer
You need to pass the CURRENT class to super
, not the parent. So:
JavaScript
1
2
1
super(Employee,self).__init__()
2
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:
JavaScript
1
2
1
super().__init__(0)
2