Skip to content
Advertisement

How to implement abstract classes over mulitple inheritances? [closed]

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

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement