[Tutor] Decision matrix

Jeff Shannon jeff@ccvcorp.com
Thu Feb 13 20:05:01 2003


Erik Price wrote:

>
> Jeff Shannon wrote:
>
>> The string sequence is used for strings. ;)  Strings are a sequence 
>> all on their own, which is why you can do things like:
>>
>>  >>> for char in "I am a string!":
>> ...     print char, ord(char)
>
>
> Oh.  So then, it's similar to an interface or protocol?  As in, you 
> can perform X with a sequence, and of course the implementation of the 
> sequence will do the work of figuring out how to handle the situation? 
> (I started a concurrent thread on this very topic earlier today.)


Yes.  Python has quite a number of informal protocols, and any object 
that supports certain actions is said to conform to that protocol.  For 
instance, you'll find many references in the docs to "file-like objects" 
-- Python doesn't care whether it's *actually* a file object or not, as 
long as it has write(), read(), readlines() (and sometimes seek() and 
tell(), etc) methods.  In fact, there's a library object (StringIO) that 
wraps a file-like interface around a normal (presumably long) string. 
 There's also a sequence protocol, which involves responding 
appropriately to indexing, slicing, iteration, and the like.  You can 
even write your own sequences -- just create a class that defines 
__getitem__(), __setitem__(), __len__(), etc. -- just as you can write 
your own file-like objects and your own dict-like objects.

Jeff Shannon
Technician/Programmer
Credit International