Class Variable Access and Assignment
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Thu Nov 3 07:36:02 EST 2005
On Thu, 03 Nov 2005 11:55:06 +0000, Antoon Pardon wrote:
> No matter wat the OO model is, I don't think the following code
> exhibits sane behaviour:
>
> class A:
> a = 1
>
> b = A()
> b.a += 2
> print b.a
> print A.a
>
> Which results in
>
> 3
> 1
Seems perfectly sane to me.
What would you expect to get if you wrote b.a = b.a + 2? Why do you expect
b.a += 2 to give a different result?
Since ints are immutable objects, you shouldn't expect the value of b.a
to be modified in place, and so there is an assignment to b.a, not A.a.
On the other hand, if this happened:
py> class A:
... a = []
...
py> b = A()
py> b.a.append(None)
py> print b.a, A.a
[None], []
*then* you should be surprised.
(Note that this is not what happens: you get [None], [None] as expected.
The difference is that append modifies the mutable list in place.)
--
Steven.
More information about the Python-list
mailing list