Python乘法继承

2024-04-24 14:42:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python实现一些数学结构。从中继承许多其他类的基类是矩阵类。对于此类,实现了一个乘法:

def __mul__(self, other):

    if isinstance(other,matrix):
        if not self._type._ncols == other._type._nrows:
            raise ValueError('Cannot multiply matrix of type "{0}" with matrix of type "{1}"'.format(self._type, other._type))
        arr=[[sum([val1*val2 for val1,val2 in zip(row,col)]) for col in other.columns()] for row in self._array]
        self._type=matrix_type(array=arr)
        self._array=arr
        return self
    else:
        arr = [[val*other for val in row] for row in self._array ]
        self._type=matrix_type(array=arr)
        self._array=arr
        return self

这很好,但是如果我将继承自matrix类的一个类(名为“spinor”)的两个实例相乘,结果是matrix类的实例,而不是派生spinor类的实例。这是一个问题,因为spinor类在乘法之后有一些我需要的附加功能。在

有没有一种实现乘法的方法是这样的:返回类型是反映派生类的类型的?在

谢谢!在


Tags: of实例inselfforiftypearray