[Tutor] __setitem__

Gregor Lingl glingl at aon.at
Thu Feb 26 18:23:31 EST 2004

Hi Christopher!

>What does __setitem__ do?  From reading the docs, I
>think it has something to do with setting values in a
... hmmm... better:  in an object ...  Let's see ...

First an example:

 >>> class A:
    def __init__(self, n):
        self.data = [0]*n    # a list of n zeros
    def __setitem__(self, i, val):
        self.data[i] = val
    def __getitem__(self, i):
        return self.data[i]

 >>> a=A(10)
 >>> a[3]="huuu!"
 >>> for i in range(5):
    print a[i]


Conclusion: if a class A defines the special method __setitem__
it  makes the expression   a[i]  meaningful for any instance a of A.
So you can set values via an index. Of cours you must provide

 >>> a[12]="outch!"

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in -toplevel-
  File "<pyshell#7>", line 5, in __setitem__
    self.data[i] = val
IndexError: list assignment index out of range

This doesn't work, since the data attribute has length 10 only.

In the same way the __getitem__ special method lets you access
the components of a.data via the [...] - operator.

Do you have some previous experience with procramming with classes
in Python? If not, tinkering with special methods isnot a very
good starting point, I think ...


>"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
>-David Bowie
>"Who dares wins"
>-British military motto
>"The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter
>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list