[Tutor] instance variables and the instance dictionary
Gonçalo Rodrigues
op73418@mail.telepac.pt
Thu Jan 9 18:04:01 2003
----- Original Message -----
From: "Poor Yorick" <gp@pooryorick.com>
To: <tutor@python.org>
Sent: Thursday, January 09, 2003 4:54 PM
Subject: [Tutor] instance variables and the instance dictionary
> 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)
Or, more elegantly:
self.__dict__['var1'] = 5
>
Let me answer with another question: why do you need this second
alternative?
The statement
self.var1 = 5
may trigger some method calls (via __setattr__, via properties, etc.) so, by
using self.__dict__ you may be breaking encapsulation and, in general,
making a mess of instance data.
> Poor Yorick
> gp@pooryorick.com
>
All the best,
G. Rodrigues