Style question - defining immutable class data members

Steve Holden steve at holdenweb.com
Fri Mar 27 02:47:40 EDT 2009


John Posner wrote:
> [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
> 
That amendment would probably be least confusing to new readers, though
it would help when in hypermedia to link "property" to some discussion
of properties as they apply on the various Python versions.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
Holden Web LLC                 http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/




More information about the Python-list mailing list