Skip to main content
 首页 » 编程设计

python + 运算符重载问题

2025年05月04日10insus

我正在尝试实现 Matrix 的加法功能。 (也就是两个矩阵相加) 我通过重载加法函数来做到这一点,以便可以添加两个矩阵。 对于这个Matrix类,我继承了Grid类来实现。

我似乎在此处的 __add__ 方法中遇到了问题,但我很清楚。错误显示 AttributeError: 'Matrix' Object has no attibute '_data'。

这是我的代码。请问有人可以帮忙吗?或者解释一下?

谢谢

from Grid import Grid 
 
class Matrix(Grid): 
    def __init__(self, m, n, value=None): 
        self.matrix = Grid(m, n) 
        self.row = m 
        self.col = n 
    def insert(self, row, col, value): 
        self.matrix[row][col] = value 
        print self.matrix 
    def __add__(self, other): 
        if self.row != other.row and self.column != other.column: 
            print " Matrixs are not indentical." 
        else: 
            for row in xrange(self.row): 
                for col in xrange(self.col): 
                    self.matrix[row][col] = self.matrix[row][col] + other[row][col] 
        return self.matrix  

这是我继承的 Grid 类。

from CArray import Array 
 
class Grid(object): 
    """Represents a two-dimensional array.""" 
    def __init__(self, rows, columns, fillValue = None): 
        self._data = Array(rows) 
        for row in xrange(rows): 
            self._data[row] = Array(columns, fillValue) 
    def getHeight(self): 
        """Returns the number of rows.""" 
        return len(self._data) 
    def getWidth(self): 
        "Returns the number of columns.""" 
        return len(self._data[0]) 
    def __getitem__(self, index): 
        """Supports two-dimensional indexing  
        with [row][column].""" 
        return self._data[index] 
    def __str__(self): 
        """Returns a string representation of the grid.""" 
        result = "" 
        for row in xrange(self.getHeight()): 
            for col in xrange(self.getWidth()): 
                result += str(self._data[row][col]) + " " 
            result += "\n" 
        return result 

请您参考如下方法:

您没有调用继承的类构造函数,因此,_data 未在您的类中定义。尝试在 Matrix init 中添加以下内容:

super(Matrix, self).__init__(m, n, fillValue=value)