__dict__ is neato torpedo!

Ian Kelly ian.g.kelly at gmail.com
Sat Jun 11 23:08:40 EDT 2011


On Sat, Jun 11, 2011 at 8:21 PM, Andrew Berg <bahamutzero8825 at gmail.com> wrote:
> On 2011.06.11 09:12 PM, Terry Reedy wrote:
>> On 6/11/2011 9:32 PM, Andrew Berg wrote:
>> > I'm pretty happy that I can copy variables and their value from one
>>
>> You are copying names and their associations, but not the objects or
>> thier values.
> Associations? The update() method copies the values; a.val1 and b.val1
> point to two different places in memory.

Incorrect.  The names in b will be bound to the same objects as the
names in a, not to copies of them.  For immutable objects such as
ints, this doesn't matter.  For mutable objects such as lists, it can:

>>> class X(object):
...   pass
...
>>> a = X()
>>> b = X()
>>> a.foo = ['apples']
>>> b.__dict__.update(a.__dict__)
>>> a.foo
['apples']
>>> b.foo
['apples']
>>> a.foo.append('oranges')
>>> a.foo
['apples', 'oranges']
>>> b.foo
['apples', 'oranges']

Cheers,
Ian



More information about the Python-list mailing list