Class Variable Access and Assignment
steve at REMOVETHIScyber.com.au
Thu Nov 3 13:36:02 CET 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
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> print b.a, A.a
*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.)
More information about the Python-list