python +运算符重载问题

use*_*092 1 python

我正在尝试实现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 
Run Code Online (Sandbox Code Playgroud)

这是我继承的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
Run Code Online (Sandbox Code Playgroud)

rea*_*l4x 7

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

super(Matrix, self).__init__(m, n, fillValue=value)
Run Code Online (Sandbox Code Playgroud)