【问题标题】:Conditional python class inheritance条件python类继承
【发布时间】:2021-04-22 16:52:24
【问题描述】:

我有一些类继承。

class A1:
    def __init__(self, b):
        self.b = b

    def some_A_function():
        print("This is A1 function")

    # ... more A1 specific functions

class B(A1):
    def __init__(self, a, b):
        super().__init__(b)
        self.a = a

    # ... more B specific functions

class C(B):
    def __init__(self, a, b)
        super().__init__(a, b)
    # ... more C specific functions

if __name__ == "__main__":
    # Main instance
    a = 1
    b = 2
    C_obj = C(a, b)

现在,A2类的一些介绍如下:

class A2:
    def __init__(self, b):
        self.b = b

    def some_A_function():
        print("This is A2 function")

现在,根据在创建类C 的实例时传递的a 的值,预计类B 的继承会发生变化。例如,如果a=1,则B 继承类A1,否则继承类A2

我不想将任何代码更改为 A1A2Cmain 类,因为它周围有大量代码,实际上很难对其进行重组反正。但是,我可以通过更改B 中的某些内容或调用一些独立的函数来实现基于a 的值的逻辑来决定B 的继承。

我一般是工厂功能的新手。我在搜索中找到的大多数示例都是在层次结构的最顶层实现的,它评估条件并返回类的相关实现(类似于 if a==1,return C1 else C2。但是,在我的情况,我不知道怎么说C类(在main函数中)要求B类继承A的两个实现之一(即A1A2)基于作为变量 a 传递的值。

【问题讨论】:

  • 我已经看过那个了。问题是,我无法对这个层次结构进行大规模重组。另一件事是,已在接受的答案中对层次结构最高级别的类进行了更改。就我而言,__bases__ 的更改需要发生在最低级别的层次结构中。我没有处理程序来更改 bases 属性。

标签: python python-3.x inheritance python-class


【解决方案1】:

我猜这不是最干净的解决方案,但可以通过这种方式实现:

class A1:
    def __init__(self, b):
        self.b = b
    def some_A_function(self):
        print("This is A1 function", "b = " + str(self.b))

class A2:
    def __init__(self, b):
        self.b = b
    def some_A_function(self):
        print("This is A2 function", "b = " + str(self.b))

def get_class_B(base):
    class B(base):
        def __init__(self, a, b):
            super().__init__(b)
            self.a = a
    return B

def create_obj_C(a, b):
    if (a == 1): base = get_class_B(A1)
    elif (a == 2): base = get_class_B(A2)

    class C(base):
        def __init__(self, a, b):
            super().__init__(a, b)

    return C(a,b)

那么你必须通过辅助方法create_obj_C创建C

create_obj_C(1, 2).some_A_function() # "This is A1 function, b = 2"
create_obj_C(2, 8).some_A_function() # "This is A2 function, b = 8"

【讨论】:

  • 这种方式在我看来是不可扩展的,即如果从A->B->C->D->E有多重继承,携带条件会有点困难变量到最低级别而不更改预先存在的类定义,这并不总是可能的。但是,您的解决方案至少确实帮助我为我的案例找到了正确的实施方案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多