我學習Python類,我創建了一個類叫做多項式,並正嘗試添加兩個多項式,但總是會收到以下錯誤消息類多項式
soma.termos[i] = self[i] + other[i] TypeError: 'Polinomio' object does not support indexing to fix
解決我創建的是一個屬性向量的大小,並創建一個大小爲n的零向量,但仍然錯誤仍然存在,出了什麼問題?
class Polinomio:
def __init__ (self, termos = [], n = 0):
self.termos = termos
self.n = [0] * n
def __len__ (self):
return len(self.termos)
def __setitem__ (self, i, x):
self.termos[i] = x
def __add__ (self, other):
soma = Polinomio(n = len(self.termos))
for i in range(len(self.termos)):
soma.termos[i] = self[i] + other[i]
def print (self):
print(self.termos)
p1 = Polinomio([1, 2, 3])
p2 = Polinomio([1, 2, 3])
p2.print()
p3 = Polinomio()
p3 = p1 + p2
可能重複[Python:Object不支持索引](https://stackoverflow.com/questions/22463866/python-object-does-not-support-indexing) –