2017-01-19 8 views
-1

표준 연산자 (+, *, -)에 과부하를 걸어야하는 프로그래밍 클래스에 대한 과제를 수행하고 작동하도록하십시오. 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 
+0

에 직접'대신 self.matrix_add''matrix_add'을 목록을 보낼 수 있습니다. – Arman

+0

그리고 심지어 내가 쓸 때 : 반환 self.matrix_add를 (A, B) 나는 당신이 matirx_add'에 매개 변수로'A'을 통과 필요하지 않습니다 – BadMan

+0

형 매트릭스의 오브젝트가 렌을 (이 없습니다 또 다른 오류 메시지)를 얻을 '그냥 클래스 속성,'a.self' 대신'a'를 사용하십시오 – Arman

답변

0

은 __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 self.matrix_add(self.a, b.a) 

     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]]) 
    print(A+B) 
+0

감사합니다 !!! 하지만 b.a는 무엇을합니까? in self.matrix_add (self.a, b.a) – BadMan

+0

객체 b의 목록 a를 보냅니다 – SmartManoj

+0

Genius! 감사! :) 당신은 꽤 똑똑한 사람입니다. – BadMan

0

를 앞에 self (@Arman이 말했듯이) matrix_add 함수 호출과 implement a __len__(self) function :

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 self.matrix_add(self.a, b) 

    def __len__(self): 
     # TODO: FILL THIS IN 
     pass 

    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)] 

이 후에도 구현해야하는 또 다른 기능을 묻는 또 다른 오류가 표시됩니다. 구글이, 그리고 행운 ;-)