包含派生类列表的类

时间:2019-05-12 20:50:23

标签: python class inheritance

假设我具有以下基类和派生类,举例说明了类继承的基本情况:

class base(object): 
    type   = []                  
    def __init__(self,arg1,arg2):
        self.m1 = arg1
        self.m2 = arg2

class derivedA(base):    # inherits from base
    type = 'A'  
    base.type.append('A')
    def value(self,arg):
        return arg*0.345

class derivedB(base):
    type   = 'B'
    base.type.append('B')
    def value(self,arg):
        return arg*0.186

现在假设我想定义另一个类,该类包含从base派生的任何类的列表作为成员:

class container(object):
    def __init__(self,dim=None,tp=None):
        assert dim>=0
        if dim==0:
            self.dim = 0
            self.lst = [ ]
            self.mlt = [ ] 
        else:
            assert tp!=None
            self.dim = dim
            self.lst = [base(0,0) for _ in range(dim)] # how to call generic constructor of class?
            self.mlt = [1.0] * dim

    def printVals(self,value):
        for d in self.lst:
            print(d.value(value))

我如何能够从作为参数传递的类型tp中推断出适当的构造函数?实际上,它仅实例化base类成员的列表:

gg = container(10,derivedA.type)
gg.printVals(0.5) # 'base' object has no attribute 'value'

1 个答案:

答案 0 :(得分:1)

我觉得您不太习惯类是Python中的对象。您不需要字符串作为类的占位符。您可以直接传递类。

所有type的东西都是毫无意义的。直接通过课程:

class Base(object): 
    def __init__(self, arg1, arg2):
        self.m1 = arg1
        self.m2 = arg2

class DerivedA(Base):
    def value(self, arg):
        return arg*0.345

class DerivedB(Base):
    def value(self, arg):
        return arg*0.186

class Container(object):
    def __init__(self, dim=None, tp=None):
        if dim is not None and dim < 0:
            raise ValueError('dim must be positive')
        if not dim:
            self.dim = 0
            self.lst = []
            self.mlt = [] 
        else:
            if tp is None:
                raise TypeError('tp must be provided if dim is provided')
            self.dim = dim
            self.lst = [tp(0, 0) for _ in range(dim)]
            self.mlt = [1.0] * dim

    def print_vals(self, value):
        for d in self.lst:
            print(d.value(value))

gg = Container(10, DerivedA)
gg.print_vals(0.5)

请注意,在DerivedA调用中使用derivedA.type而不是Container,在tp(0, 0)构造函数中使用Container调用。