I'm trying to make a 2D array class, and ran into a problem. The best way I could figure out to do it was to pass get/setitem a tuple of the indices, and have it unpacked in the function. Unfortunately though, the implementation looks really messy:
class DDArray:
data = [9,8,7,6,5,4,3,2,1,0]
def __getitem__ (self, index):
return (self.data [index [0]], self.data [index [1]])
def __setitem__ (self, index, value):
self.data [index [0]] = value
self.data [index [1]] = value
test = DDArray ()
print (test [(1,2)])
test [(1, 2)] = 120
print (test [1, 2])
I tried just having it accept more parameters:
class DDArray:
data = [9,8,7,6,5,4,3,2,1,0]
def __getitem__ (self, index1, index2):
return (self.data [index1], self.data [index2])
def __setitem__ (self, index1, index2, value):
self.data [index1] = value
self.data [index2] = value
test = DDArray ()
print (test [1, 2])
test [1, 2] = 120
print (test [1, 2])
but that results in a weird type error telling me that I'm not passing enough arguments (I guess anything inside of the subscript operator is considered 1 argument, even if there's a comma).
(Yes, I know, the above class isn't actually a 2D array. I wanted to have the operators figured out before I moved on to actually making it 2D.)
Is there a standard way of doing it that looks a little cleaner?
Thanks
See Question&Answers more detail:
os