I've created a python program that makes a vector. Now i want to set an item using a function__setitem__
and__getitem__
. So for example, ifvector = Vec()
andvector[3] = 26
would change an empty vector to[0, 0, 0, 26]
. I need to override the__getitem__
and__setitem__
I've listed the code below, but i'm having troubles with the get and set functions. Any advice?
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
def __getitem__(self, key):
return self.vector[key]
The problem is the vector you created has no length because of the default value given the
length
keyword argument in the__init__()
method definition. Try this:You need to adapt your
__getitem__
and__setitem__
to delegate to the underlying list:It would be easier in
__str__
if you do thisYou have several problems:
extend
is appending essentially a new vector to the end of the original, rather than increasing the length of the original. It's not clear that it needs to return a string representation of the modified vector (unless it's just for debugging purposes).__setitem__
needs to callextend
if the key is too large.__getitem__
needs to access the underlying list, not use an undefined attribute