some random reflections of a "Python newbie": (2) language issues
Paul M
paul.m at yale.edu
Thu Dec 9 10:59:18 EST 1999
Alex,
If I read your post correctly, what you're looking forward is already
in python. You can make your own objects sequence like by defining the
special sequence operator methods (__len__, __getitem__, __setitem__,
__delitem__) in the class definition. See section 3.3 of the Python
Reference Manual for more info.
In the following example I define the __getitem__ method of my object
so that a call of "for item in seq" iterates backwards over the
internal data list. It would be easy to come up with an example where
the internal data didn't involve a sequence at all.
seqlike.py
----------
class sequence_like:
def __init__(self):
self.data = []
def __getitem__(self, key):
return self.data[-(key+1)]
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
IDLE 0.5 -- press F1 for help
>>> import seqlike
>>> a = seqlike.sequence_like()
>>> a.data = range(20)
>>> for i in a: print i,
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
>>>
The python documentation and FAQ is chock full of good stuff waiting
to be found. Read 'em and absorb 'em!
--Paul
Alex Martelli wrote in message <82od57$i7n$1 at serv1.iunet.it>...
>
>4. why can't I overload "in" to have the
> expected semantics and maybe be fast...?
>
>"if a in X:" and "for a in X:" will now both
>give errors unless X is a sequence. But
>it would seem much more useful, elegant,
>natural, polymorphic, and whatever other
>buzzwords you desire, if there was some
>__whatever__ method, or methods, that
>I could overload on my object X, to make
>these operations work, without wanting to
>make X a sequence (besides, for the
>"if a in X" case, I could give my true/false
>answer much faster than the currently
>rigid linear-iteration semants of "in"...!).
>
>It's a pity to have to write, say,
> if X.hasElement(a):
>rather than the natural
> if a in X
>and it's a net loss of polymorphism, without
>any compensating gain that I can see.
>
>The way I envision this -- if X chooses to
>implement a method __contains__, then,
>for an "a in X" test, that method is called,
>with a as an argument, and its return
>value is taken as the test's result. If X
>has no such method, then we're back to
>the current semantics of "if a in X", i.e.,
>X must be a sequence, etc etc.
[snip]
More information about the Python-list
mailing list