首页 > 解决方案 > 矩阵类方法中的参数错误 - Python

问题描述

我在 python 3 中创建了矩阵类(到目前为止我只创建了一种方法):

class Matrix() :
    __rows = []
    __columns = []
    def SetRows(self,rows) :
        self.__rows = rows
        i = 0
        while i < len(rows[0]) :
            a = []
            j = 0
            while j < len(rows) :
                a.append(rows[j][i])
                j += 1
            self.__columns.append(a)
            i += 1
m = Matrix
m.SetRows([[0,8,56],[98,568,89]])

但它给出了这个错误:

Traceback (most recent call last):
  File "f:\PARSA\Programming\Python\2-11-2.py", line 14, in <module>
    m.SetRows([[0,8,56],[98,568,89]])
TypeError: SetRows() missing 1 required positional argument: 'rows'

我已经输入了“行”参数。显然,我不需要输入“自我”。我将 VS Code 用于 IDE。谢谢你的帮助。

标签: pythonclassmethodsarguments

解决方案


您的功能一切正常。

您只是在实例化时忘记了括号m=Matrix()。所以解释器认为你必须指定 self,因为它不识别类。

编辑:我刚刚认识到另一个问题。你实际上用这些循环创建了一个无限while循环。如果您不添加分配 i 和 j ,它们将始终分别保持在len(rows[0])下方len(rows)

所以:

class Matrix() :
    __rows = []
    self.__columns = []
    def SetRows(self,rows) :
        self.__rows = rows
        i = 0
        while i < len(rows[0]) :
            a = []
            j = 0
            while j < len(rows) :
                a.append(rows[j][i])
                j += 1
            self.__columns.append(a)
            i += 1

m = Matrix()
m.SetRows([[0,8,56],[98,568,89]])

推荐阅读