[Tutor] __getitem__
Kent Johnson
kent37 at tds.net
Mon Jan 16 22:27:36 CET 2006
Christopher Spears wrote:
> I understand that you can use __getitem__ as a hook to
> modify indexing behavoir in a class. That's why
> __getitem__ not only affects [] but also for loops,
> map calls, list comprehension, etc. For loops, etc.
> work by indexing a sequences from zero to a higher
> index until out-of-bounds is reached. But why does
> this work?
>
>
>>>>class stepper:
>
> ... def __getitem__(self, i):
> ... return self.data[i]
> ...
>
>>>>'p' in X
>
> True
>
> What does 'in' have to do with indexing?
How do you suppose 'in' works? To see if something is in a list, for
example, you have to iterate over each element of the list and check if
it is the item you expect.
Under the hood, Python will use the __contains__() or __getitem__()
special method of a class to evaluate 'x in y'.
Loosely speaking, if y is an instance of a class that implements
__getitem__() but not __contains__(), 'x in y' is more or less the same
as this:
def in(x, y):
for i in y:
if i == x:
return True
return False
From the language reference:
"For user-defined classes which do not define __contains__() and do
define __getitem__(), x in y is true if and only if there is a
non-negative integer index i such that x == y[i], and all lower integer
indices do not raise IndexError exception. (If any other exception is
raised, it is as if in raised that exception)."
http://docs.python.org/ref/comparisons.html#l2h-432
Kent
More information about the Tutor
mailing list