Style question - defining immutable class data members

John Posner jjposner at snet.net
Fri Mar 27 04:47:14 CET 2009


[snip]
 >> >     If the object is a class instance and the attribute reference
occurs
 >> >     on both sides of the assignment operator; for example::
 >> > 
 >> >         self.x = self.x + 1
 >> >
 >> >     ... in the RHS expression, ``self.x`` is evaluated with 
 >> >     ``getattr()``, which can access either an instance attribute or
(if 
 >> >     no instance attribute exists) a class attribute. The LHS target 
 >> >     ``self.x`` is assigned with ``setattr()``, which *always* accesses

 >> >     an instance attribute, creating it if necessary. Thus, the two 

Steve Holden said: 

 >> Is this true in the case of read-write properties? This 
 >> seems a little
 >> simplistic for what's actually a pretty complex piece of logic.

It's not true for the read-write property example in the official property()
function description:

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")


But it *is* true if you revise this class definition to follow the pattern
under discussion: a class attribute provides the "initial value" of an
instance attribute:

class C(object):
    _x = 0
    
    def __init__(self):
        pass
    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    x = property(getx, setx)


My intent was to fix an obvious omission: a special case was discussed in
the "Augmented assignment statements" section, but an almost-identical
special case was omitted from the "Assignment statements" section.

Neither section currently mentions property attributes. Do you think both
sections should be changed to cover property attributes? Or maybe it would
be simpler just to revise my first sentence:

  from: If the object is a class instance
    to: If the object is a (non-property) class instance





E-mail message checked by Spyware Doctor (6.0.0.386)
Database version: 5.12050
http://www.pctools.com/en/spyware-doctor-antivirus/



More information about the Python-list mailing list