I have a question on multi level inheritance. I am trying to write classes of the form:
JavaScript
x
49
49
1
from abc import ABC, abstractmethod
2
import numpy as np
3
4
### Parent class
5
class A(ABC):
6
@abstractmethod
7
def eval(self, x: np.ndarray) -> np.ndarray:
8
pass
9
10
@abstractmethod
11
def func(self, x: np.ndarray) -> None:
12
pass
13
14
### 1. Inheritance
15
class B1(A):
16
def eval(self, x: np.ndarray) -> np.ndarray:
17
#do something here
18
return np.zeros(5)
19
20
@abstractmethod
21
def func(self, x: np.ndarray) -> None:
22
pass
23
24
class B2(A):
25
def eval(self, x: np.ndarray) -> np.ndarray:
26
#do something different here
27
return np.zeros(10)
28
29
@abstractmethod
30
def func(self, x: np.ndarray) -> None:
31
pass
32
33
### 2. Inheritance
34
class C1(B1):
35
def func(self, x: np.ndarray) -> None:
36
print('child1.1')
37
38
class C2(B1):
39
def func(self, x: np.ndarray) -> None:
40
print('child1.2')
41
42
class C3(B2):
43
def func(self, x: np.ndarray) -> None:
44
print('child2.1')
45
46
c1 = C1()
47
c2 = C2()
48
c3 = C3()
49
I am not planning on instantiating A
B1
or B2
.
My question is, if this is the correct way to go about this in python? I want to make it clear that Bx
are still abstract classes
Advertisement
Answer
Its quite simple. If class A
defines some abstract methods, then any other class which inherits from A
also inherits these methods. Not need to reimplement as abstract methods.
In your case your Bx
classes only need their specialised implementations of eval()
. They don’t need func()
since they already inherit them.