How to make slicing and other methods interact?

Tim Churches tchur at optushome.com.au
Mon Jun 2 07:35:07 EDT 2003


What is the general pattern for making methods interact? For example, I
define a class with overridden __str__ and __getslice__ methods. If I
print an instance of the class, the __str__ method is used. But if I
print a  slice of the instance, only the __getslice__ method is called,
but not __str__.

###################################
class test(object):
	def __init__(self,iterable):
		self._data = iterable
	def __str__(self):
		xlate = {1:'one',2:'two',3:'three',4:'four',5:'five'}
		ret = ['[']
		for x in self._data:
			ret.append(xlate[x])
		ret.append(']')
		return '\n'.join(ret)
	def __getslice__(self,low,high):
		return self._data[low:high]

t = test([1,2,3,4,5])

print t
print
print t[1:3]
###################################

Produces this output:

 [
one
two
three
four
five
]

[2, 3]

When what I really want is:

[
one
two
three
four
five
]

[
two
three
]

Is there a general way of achieving this - so that slicing (or indexing)
semantics propagate to other methods?

Tim C








More information about the Python-list mailing list