【发布时间】:2017-01-19 10:35:27
【问题描述】:
我正在为一个编程类做作业,我需要重载标准运算符(+、*、-)并让它们与 Matrix 类对象一起工作。我认为我做得很好,但是 Python 不断吐出一个名称错误,我不知道为什么,因为函数已定义。
我已经尝试了很多东西,但我仍然不断地回到我的原始代码(如下)。请帮忙
class Matrix:
"""A Class Matrix which can implement addition, subtraction and multiplication
of two matrices; scalar multiplication; and inversion, transposition and
determinant of the matrix itself"""
def __init__(self, a):
"""Constructor for the Class Matrix"""
#what if you only want to work with one matrix
self.a = a
def __add__(self, b):
return matrix_add(self.a, b)
def matrix_add(self, a, b):
"""
Add two matrices.
Matrices are represented as nested lists, saved row-major.
>>> matrix_add([[1,1],[2,2]], [[0,-2],[3,9]])
[[1, -1], [5, 11]]
>>> matrix_add([[2,3],[5,7]], [[11,13],[17,19]])
[[13, 16], [22, 26]]
>>> matrix_add([[2,3,4],[5,7,4]], [[11,13,1],[17,19,1]])
[[13, 16, 5], [22, 26, 5]]
>>> matrix_add([[1,2],[3,4]],[[1,2]])
Traceback (most recent call last):
...
MatrixException: matrices must have equal dimensions
"""
rows = len(a) # number of rows
cols = len(a[0]) # number of cols
if rows != len(b) or cols != len(b[0]):
raise MatrixException("matrices must have equal dimensions")
return [[a[i][j] + b[i][j] for j in range(cols)] for i in range(rows)]
我使用以下方式调用它:
A = Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
B = Matrix([[2, 3, 4], [2, 3, 4], [2, 3, 4]])
我收到此错误消息:
----------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-113-74230a6e5fb2> in <module>()
----> 1 C = A + B
<ipython-input-110-e27f8d893b4d> in __add__(self, b)
22 def __add__(self, b):
23
---> 24 return matrix_add(self.a, b)
25
NameError: name 'matrix_add' is not defined
【问题讨论】:
-
self.matrix_add代替matrix_add在__add__函数中。 -
即使我写:return self.matrix_add(a, b) 我得到另一个矩阵类型的错误消息对象没有 len()
-
您不需要将
a作为参数传递给matirx_add,只需将其用作类属性,a.self而不是a -
@RicardoMartinez:当然,也可能有 other 错误,但是 in your question 中发布的错误是由于缺少使用 @987654331 造成的@.
-
@RicardoMartinez:您在
Matrix实例上调用len()。您没有提供__len__方法,因此 also 中断。
标签: python overloading nameerror