gpt4 book ai didi

python + 运算符重载问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:23 25 4
gpt4 key购买 nike

我正在尝试实现 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)

关于python + 运算符重载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8867944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com