[Tutor] instance variables and the instance dictionary
Magnus Lycka
magnus@thinkware.se
Thu Jan 9 18:48:02 2003
At 09:54 2003-01-09 -0700, Poor Yorick wrote:
>In an instance, are the following statements equivalent? Are there any
>caveats to setting an instance variable the second way?
>
>self.var1 = 5
>
>self.__dict__.__setitem__('var1', 5)
As others have mentioned, manipulating the __dict__ bypasses
__setattr__. A consequence of this is that the code in an
implementation of __setattr__ often uses __dict__ manipulation
to avoid infinite recursion.
A method like below would call itself until the stack breaks.
def __setattr__(self, attr, val):
# do some error checks
...
setattr(self, attr, val)
You need to do:
def __setattr__(self, attr, val):
# do some error checks
...
self.__dict__[attr] = val
instead.
But note!
DANGER!!!
What will happen if attr is '__private' ???
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se