emulating sequences

Hans Nowak hnowak at cuci.nl
Fri Aug 31 11:00:57 EDT 2001


>===== Original Message From John Hunter <jdhunter at nitace.bsd.uchicago.edu> 
=====
>I have a user defined type that I would like to behave like a
>sequence, eg
>
>results = MyType()
>for result in results:
>        blah
>
>Talking about special methods, Beazley in 'Essential Python' says that
>the following methods are used by objects that want to emulate
>sequence and mapping objects:
>
>__len__, __getitem__, __setitem__, __delitem__, __getslice__,
>__setslice__, __delslice__
>
>If I implement each of these for MyType, then can I get the desired
>behavior?  If so, is there a subset that is sufficient just to get the
>'in' behavior?

Yes. You only need __getitem__:

>>> class Seq:
	def __init__(self, seq):
		self.seq = seq
	def __getitem__(self, index):
		return self.seq[index]

>>> s = Seq("cocoricoo")
>>> for c in s: print c,

c o c o r i c o o

In 2.2, you can define an iterator for this, by the way.

>Finally, if you have a sequence, what is the best way to get an index
>of the first match of a value in a find command, similar to the C++
>
>   i = find(s.begin(), s.end(), val)
>
>Is there such a function, and if so, what is the illegal value
>indicating failure to find?

Well, there's the string method find():

>>> s = "abracadabra"
>>> s.find("c")
4
>>> s.find("z")  # not in the string, obviously
-1

>>> print s.find.__doc__
S.find(sub [,start [,end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within s[start,end].  Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

HTH,

--Hans Nowak





More information about the Python-list mailing list