__getitem__?

Joshua Tompkins joshua at bladeagency.com
Fri Aug 24 11:24:28 EDT 2001


Hi.

As sort of an experiment, I'm implementing a multi-dimensional list
object in python (I'm not at sure that there's any real value in this,
as there's probably already stuff like it out there, but hey, I'm
bored).  Here's the code (27 lines):

class mdList:
	version = 0.15
	
	def __init__( self, xBound, yBound ):
		print "mdList version " + str( self.version )
		self.dataList = []
		
		self.xLength = xBound
		self.yLength = yBound

		i = 0
		
		while i < xBound:
			j = 0
			yList = []
			
			while j < yBound:
				yList.append( 0 )
				j += 1
				
			if len( yList ) > 0:
				self.dataList.append( yList )
			i += 1
		return None
		
	def __getitem__( self, key ):
		return self.dataList[key]

My question is about the __getitem__ method.  After I added it, I
could access the dataList internal variable like this (where a is the
class instance):

a[0][0]

That's pretty neat (but is that how I should be doing it?  I don't
understand how I can access the second array dimension when there's
only one argument passed to the method), but here's the real question:
 why does this (see below) work?

a[0][0] = 1

Thanks in advance,

-joshua



More information about the Python-list mailing list