【问题标题】:How can inherit from different classes depending on a condition?如何根据条件从不同的类继承?
【发布时间】:2020-11-02 16:35:33
【问题描述】:

我有两个类,A 和 B。两者都有一个 foo 方法。在某些情况下,我不想让我的类 C 从 A 继承 foo (和其他方法),而在其他情况下从 B 继承。在代码示例中,C 将始终具有来自 A 的 foo 方法:

class A:
    def foo(self):
        print('A.foo()')


class B:
    def foo(self):
        print('B.foo()')


class C(A, B):
    pass


C().foo()

如何选择继承哪个 foo 方法?喜欢:

class C(A,B):
    def __init__(self, inherit_from):
        if inherit_from == "A":
            # inherit methods from A
        elif inherit_from == "B":
            # inherit methods from B

【问题讨论】:

  • 这让我觉得是XY Problem
  • 嗯,也许 - 我有一个支持不同类型相机的头位估计包。每个相机都有获取图像、设置分辨率等的特定功能 - 其余过程是相同的(将图像馈送到位姿估计器等)。因此,应根据所连接的相机使用正确的功能。我认为最简洁的方法是为每种相机类型设置一个类,然后继承我需要的类

标签: python inheritance multiple-inheritance


【解决方案1】:

您不想让C 成为一个子类,而是一个超类,并在初始化对象时而不是在定义类时决定创建哪种类型的对象:

from abc import abstractmethod

class C:
    @abstractmethod
    def foo(self) -> None:
         pass

class A(C):
    def foo(self):
        print('A.foo()')

class B(C):
    def foo(self):
        print('B.foo()')

inherit_from = input("What type of C should I foo?")
if inherit_from == 'A':
    c: C = A()
elif inherit_from == 'B':
    c = B()
else:
    raise ValueError(f"unknown C subclass {inherit_from}")

c.foo()

请注意,这仅在您使用类型检查时才真正重要(即,您希望能够保证 c 将是一个实现 foo 方法的对象 - C 超类为您提供了一种无需提前指定是A 还是B 的方法。如果你不使用类型检查,那么你可以完全跳过定义类C

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 2014-01-11
    • 2010-09-20
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    相关资源
    最近更新 更多