简体   繁体   English

错误:“矩阵”object 不可下标

[英]Error: 'Matrix' object is not subscriptable

I have created a class in python for matrices and want to have different functions that when applied to a matrix object accomplishes a specific goal.我在 python 中为矩阵创建了 class 并希望具有不同的功能,当应用于矩阵 object 时可以实现特定目标。 The specific function which have an error is a function to add one matrix to another.有错误的特定 function 是 function 将一个矩阵添加到另一个矩阵。

class Matrix:
  def __init__(self, rows):
    self.rows = rows    
    self.m = len(rows) 
    self.n = len(rows[0])


  def add(self,other):
     output = [[0 for x in range(self.m)] for y in range(self.m)]
     for i in range(self.m):
       for j in range(self.n): 
         output[i][j] = self[i][j] + other[i][j]
     returnmatrix = Matrix(output)
     return returnmatrix

B = Matrix([[1,2,3], [4,5,6], [7,8,9]])
F = Matrix([[1,2,3], [4,5,6], [7,8,9]])
B.add(F)

I expect the output to be a 3x3 matrix that is the addition of matrices B and F. Error recieved is: TypeError: 'Matrix' object is not subscriptable.我希望 output 是一个 3x3 矩阵,它是矩阵 B 和 F 的加法。收到的错误是:TypeError: 'Matrix' object 不可下标。

The error comes from this line;错误来自这一行;

for j in range(self.n): 
    output[i][j] = self[i][j] + other[i][j]

You are subscripting the object but presumably need to be subscripting the rows attribute:您正在为 object 下标,但可能需要为rows属性下标:

for j in range(self.n): 
    output.rows[i][j] = self.rows[i][j] + other.rows[i][j]

Also for this to work you need to create output as an instance of Matrix before this, so the full function would be:此外,为此,您需要在此之前创建output作为 Matrix 的实例,因此完整的 function 将是:

def add(self,other):
    output = Matrix([[0 for x in range(self.m)] for y in range(self.m)])
    for i in range(self.m):
        for j in range(self.n): 
             output.rows[i][j] = self.rows[i][j] + other.rows[i][j]
    return output

Also as an aside if you are creating methods like add you should look into dunder methods (eg __add__ );另外,如果您要创建诸如add之类的方法,则应查看 dunder 方法(例如__add__ ); which will give you the nice functionality of being able to use the plus symbol to add instances of your object together.这将为您提供很好的功能,即能够使用加号将 object 的实例添加在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM