Python 中原则性的条件继承

问题描述 投票:0回答:1

我有一个继承的类

np.ndarray
:

class A(np.ndarray):
  def __new__(cls, foo: np.ndarray):
    # Operate on foo...
    x = np.array([1.]) + foo # (placeholder)

    return x

  def bar(self, x):
    # Other stuff...

我想通过检测输入是

np.ndarray
还是
cupy.ndarray
来添加与 CPU/GPU 无关的行为,并动态继承两者之一,如下所示:

class A:
  def __new__(cls, foo: Union[np.ndarray, cupy.ndarray]):
    xp = cupy.get_array_module(foo) # Returns either `numpy` or `cupy` depending on `foo`

    # Operate on foo...
    x = xp.array([1.]) + foo # (placeholder)

    return xp.__new__(cls, x)

  def bar(self, x):
    # Other stuff...

我认为以下方法可能有效,但非常混乱:

class BaseA(ABC):
  def bar(self, x):
    # Other stuff...

class ANumpy(BaseA, np.ndarray):
  pass

class ACupy(BaseA, cupy.ndarray):
  pass

class A:
  def __new__(cls, foo: Union[np.ndarray, cupy.ndarray]):
    if isinstance(foo, cupy.ndarray):
      return ACupy(foo)

    return ANumpy(foo)

我该如何正确地/做好它?

python inheritance
1个回答
0
投票

def create_class(条件): 如果条件=='A': 父类 = BaseA 别的: 父类 = BaseB

class DynamicClass(parent_class):
    def __init__(self, value):
        self.value = value

    def display(self):
        return f"{self.value} with {self.action()}"

return DynamicClass
© www.soinside.com 2019 - 2024. All rights reserved.