Why aren't colons optional?
Alex Martelli
aleax at aleax.it
Sun Jan 20 17:04:50 EST 2002
Roy Smith wrote:
> Alex Martelli <aleax at aleax.it> wrote:
>
>> No, it would have substantially impoverished the language:
>>
>> class doubleface:
>> def __getitem__(self, name):
>> return "anitem"
>> def __call__(self, *args):
>> return "acall"
>
> Can you give me a practical example of why somebody would want to define a
> __getitem__ method for a class?
Up to 2.1 (or for non-new-type classes today) it's for example the only
way to enable iteration on instances. But it has of course many uses
even now that __iter__ has appeared for that purpose. For example:
class manyfuncs(list):
def __call__(self, *args, **kwds):
return [func(*args, **kwds) for func in self]
a trivially-simple application of the Multiplexer design pattern (here I
don't need to override the __getitem__ I inherit from list, but it would
be a tragedy if my __call__ was deemed to clash with it!).
Example use:
import math
trig = manyfuncs([math.sin, math.cos, math.tan])
Now I have a "function" (callable instance) trig which given any number
as argument returns a list of three results about that number. Of course
I can manipulate trig also as a list-of-functions (actually, of callables)
with indexing, slicing and so on (if I wanted to make trig immutable I
might have inherited from tuple instead, but even then I could still have
wanted to _examine_ the i-th function in the tuple, so __getitem__
remains obviously useful).
Alex
More information about the Python-list
mailing list