我创建了一个创建矢量的python程序.现在,我想设置使用功能的项目__setitem__和__getitem__.因此,例如,if vector = Vec()和vector[3] = 26将更改空向量[0, 0, 0, 26].我需要覆盖__getitem__并且__setitem__我已经列出了下面的代码,但是我遇到了get和set函数的麻烦.有什么建议?
class Vec:
def __init__(self, length = 0):
self.vector = [0]*length
def __str__(self):
return '[{}]'.format(', '.join(str(i) for i in self.vector))
#This formats the output according to the homework.
#Adds '[' and ']' and commas between each 0
def __len__(self):
return len(self.vector)
def extend(self, newLen):
self.vector.append([0]*newLen)
return (', '.join(str(j) for j in self.vector))
def __setitem__(self, key, item):
self.vector[key] = item …Run Code Online (Sandbox Code Playgroud)