Style question - defining immutable class data members

Aaron Brady castironpi at gmail.com
Sun Mar 15 13:55:25 EDT 2009


On Mar 15, 12:39 pm, John Posner <jjpos... at snet.net> wrote:
> (My apologies if the thread has already covered this.) I believe I understand the WHAT in this situation, but I don't understand the WHY ...
>
> Given this class definition:
>
>   class Cls(object):
>       x = 345
>
> ... I observe the following, using IDLE 2.6.1:
>
> >>> inst = Cls()
> >>> Cls.x is inst.x
>
> True
>
> >>> Cls.x += 1
> >>> Cls.x is inst.x
>
> True
>
> >>> inst.x += 1
> >>> Cls.x is inst.x
>
> False
>
> My question is ... WHY does the interpreter silently create the instance attribute at this point, causing a "surprising decoupling" from the class attribute? WHY doesn't the interpreter behave as it would with a simple, non-instance variable:
>
>   > python
>   Python 2.6.1 ...
>   Type "help", "copyright", "credits" or "license" for more information.
>
>   >>> x += 1
>   Traceback (most recent call last):
>     File "<stdin>", line 1, in <module>
>   NameError: name 'x' is not defined
>
> Is there a beneficial effect of silently creating the instance attribute, which outweighs the detrimental effects: (1) inconsistency, (2) the "surprising" decoupling?
>
> Tx,
> John

Yes.  If you access an attribute, you want the search to go like this:

- check instance for attribute
- check class for attribute
- check base classes for attribute

If you write an attribute, you want it stored in the attribute, not
the class or base classes.

...unless you're just picking on the augmented ops, in which case the
tradeoff is more subtle than stated.



More information about the Python-list mailing list