표준 연산자 (+, *, -)에 과부하를 걸어야하는 프로그래밍 클래스에 대한 과제를 수행하고 작동하도록하십시오. Matrix 클래스 객체. 내가 제대로하고 있다고 생각하지만 파이썬은 이름 오류가 뱉어 내고, 나는 아이디어가 없다. 왜냐하면 그 함수가 정의 되었기 때문이다.NameError가 발생했습니다. 'matrix_add'가 정의되지 않았습니다. __add__ 함수를 오버로드하려고 할 때
많은 것을 시도했지만 여전히 원래 코드로 되돌아갑니다 (아래).
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'을 목록을 보낼 수 있습니다. – Arman
그리고 심지어 내가 쓸 때 : 반환 self.matrix_add를 (A, B) 나는 당신이 matirx_add'에 매개 변수로'A'을 통과 필요하지 않습니다 – BadMan
형 매트릭스의 오브젝트가 렌을 (이 없습니다 또 다른 오류 메시지)를 얻을 '그냥 클래스 속성,'a.self' 대신'a'를 사용하십시오 – Arman