0

I have a question on multi level inheritance. I am trying to write classes of the form:

from abc import ABC, abstractmethod
import numpy as np

### Parent class
class A(ABC):
  @abstractmethod
  def eval(self, x: np.ndarray) -> np.ndarray:
    pass

  @abstractmethod
  def func(self, x: np.ndarray) -> None:
    pass

### 1. Inheritance
class B1(A):
  def eval(self, x: np.ndarray) -> np.ndarray:
    #do something here
    return np.zeros(5)

  @abstractmethod
  def func(self, x: np.ndarray) -> None:
    pass

class B2(A):
  def eval(self, x: np.ndarray) -> np.ndarray:
    #do something different here
    return np.zeros(10)

  @abstractmethod
  def func(self, x: np.ndarray) -> None:
    pass

### 2. Inheritance
class C1(B1):
  def func(self, x: np.ndarray) -> None:
    print('child1.1')

class C2(B1):
  def func(self, x: np.ndarray) -> None:
    print('child1.2')

class C3(B2):
  def func(self, x: np.ndarray) -> None:
    print('child2.1')

c1 = C1()
c2 = C2()
c3 = C3()

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

NMme
  • 461
  • 3
  • 12

1 Answers1

2

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.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Thank you! Another question: Should I inherit the `ABC` meta class also e.g. `class B1(A, ABC)` to make it clear that `B1` is still an abstract class? I am looking for the most maintainable way to go about this. – NMme Aug 17 '21 at 14:01
  • 2
    I wouldn't bother. You can call `B1` and `B2` out as being abstract in your documentation, but the inability to instantiate `B1` or `B2` will make it obvious they are abstract. – chepner Aug 17 '21 at 14:05
  • okay, thank you for the quick answer! – NMme Aug 17 '21 at 14:07