Style question - defining immutable class data members

John Posner jjposner at snet.net
Sun Mar 15 22:42:42 EDT 2009


Earlier, I said:

> I'll look into what the standard Python doc set says on this
> matter.
> 

RTFM, in section "Augmented assignment statements" of python301.chm:

---
For targets which are attribute references, the initial value is retrieved with a getattr() and the result is assigned with a setattr(). Notice that the two methods do not necessarily refer to the same variable. When getattr() refers to a class variable, setattr() still writes to an instance variable. For example:

class A:
    x = 3    # class variable
a = A()
a.x += 1     # writes a.x as 4 leaving A.x as 3
---

So, this case is closed ... almost. I believe a similar explanation, with a similar example, should appear in the preceding/parent section, "Assignment statements". Here's my proposed example:

   class A:
       x = 3         # class variable
   a = A()
   a.x = a.x + 1     # a.x on RHS gets value of class variable (3)
                     # a.x on LHS creates instance variable with
                       value of RHS expression (4)

Others' thoughts on this?

-John




More information about the Python-list mailing list