More assignment/copy novice confusion
Hans Nowak
wurmy at earthlink.net
Sun Dec 2 12:17:22 EST 2001
Arthur Siegel wrote:
>
> Given a class:
>
> >>> class p:
> def __init__(self,a):
> self.a=a
> Then -
>
> >>> m=p([1,2,3])
> >>> r=m
> >>> m.a=([1,2,4])
> >>> m.a
> [1, 2, 4]
> >>> r.a
> [1, 2, 4]
>
> clear enough.
>
> But -
>
> >>> m=p([1,2,3])
> >>> r=p([])
> >>> r.a=m.a
> >>> m.a=[1,2,4]
> >>> m.a
> [1, 2, 4]
> >>> r.a
> [1, 2, 3]
- m is an instance of p with list [1, 2, 3].
- r is an instance of p with list [].
- r.a is bound to the same object as m.a, so they both refer to
the same list [1, 2, 3].
- Now m.a is rebound to a new list [1, 2, 4]. Because r.a wasn't
rebound, it still refers to [1, 2, 3].
> And -
>
> >>> m=p([1,2,3])
> >>> r=m
> >>> r.a=m.a
> >>> m.a=[1,2,4]
> >>> m.a
> [1, 2, 4]
> >>> r.a
> [1, 2, 4]
- m is an instance of p with list [1, 2, 3].
- r is bound to the same object as m.
- r.a is bound to the same object as m.a. (Kind of redundant,
because they already referred to the same object)
- m.a is bound to [1, 2, 4].
- Since m and r refer to the same object, querying r.a returns
[1, 2, 4] too... the same list. This is unrelated to the
r.a = m.a done earlier; it has everything to do with the
r = m statement.
> But - on the theory that my confusion
> on these kinds of issues is widely shared
> among novices - I thought it worth bringing
> up for discussion, clarification.
>
> Is anything here affected by the new style classes?
I didn't study 2.2 extensively yet, but I doubt it changes
these basic binding rules.
--Hans
More information about the Python-list
mailing list