【问题标题】:I get a NameError 'matrix_add' is not define: when trying to overload the __add__ function我得到一个 NameError 'matrix_add' is not defined:尝试重载 __add__ 函数时
【发布时间】: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


【解决方案1】:

只需将列表直接发送到矩阵

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)

【讨论】:

  • 我们发送对象 b 的列表 a
【解决方案2】:

您必须缩进除第一行以外的所有行,在 matrix_add 函数调用之前加上 self(如 @Arman 所说)和 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)]

在此之后,您还会遇到另一个错误,要求您必须实现另一个功能。谷歌一下,祝你好运;-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2020-04-08
    • 2017-04-13
    • 1970-01-01
    相关资源
    最近更新 更多