python +运算符重载问题

时间:2012-01-15 06:22:11

标签: 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 

这是我继承的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

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:3)

您必须从您的孩子__init__拨打父母的__init__。将其添加到Matrix.__init__

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