How does __setitem__() work?
Bob Erb
bob at slim.instantappointment.com
Mon Jun 19 17:51:32 EDT 2000
Given the following class definition,
class Test:
def __setattr__(self, attribute, value):
print 'setting', attribute, 'to', value
self.__dict__[attribute] = value
def __setitem__(self, index, value):
print 'setting index', index, 'to', value
## THE_BLANK
I have two questions.
First, when is __setitem__ called? __setattr__() is
called when I do:
>>> t = Test(); t.list = [1,2,3]
setting list to [1, 2, 3]
I expected __setitem__ to be called when I do:
>>> t.list[0] = 7
That doesn't happen; when does __setitem__ get
called?
My second question is, to pass the assignment in
__setitem__ through, what code goes in 'THE_BLANK'
above?
(What I'm trying to do is ensure that the value of
a variable is a certain type. For instance, I want
to disallow assignment of a string value to an
integer variable. Is this anti-Python?)
Thanks for any help.
- Bob Erb
More information about the Python-list
mailing list