【问题标题】:How to implement abstract classes over mulitple inheritances? [closed]如何通过多重继承实现抽象类? [关闭]
【发布时间】:2021-10-19 10:25:51
【问题描述】:

我有一个关于多级继承的问题。 我正在尝试编写以下形式的类:

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()

我不打算实例化 A B1B2。 我的问题是,如果这是在 python 中解决这个问题的正确方法?我想明确一点,Bx 仍然是抽象类

【问题讨论】:

    标签: python python-3.x class abc


    【解决方案1】:

    这很简单。如果类A 定义了一些抽象方法,那么任何其他继承自A 的类也会继承这些方法。不需要重新实现为抽象方法。

    在您的情况下,您的 Bx 类只需要它们的专用实现 eval()。他们不需要func(),因为他们已经继承了它们。

    【讨论】:

    • 谢谢!另一个问题:我是否也应该继承 ABC 元类,例如class B1(A, ABC) 明确B1 仍然是一个抽象类?我正在寻找最可维护的方法来解决这个问题。
    • 我不会打扰。您可以在文档中将 B1B2 称为抽象,但无法实例化 B1B2 会使它们很明显是抽象的。
    • 好的,感谢您的快速回答!
    猜你喜欢
    • 1970-01-01
    • 2017-01-12
    • 2015-02-23
    • 2016-11-05
    • 2014-07-13
    • 2013-08-04
    • 2018-04-05
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多