Style question - defining immutable class data members

John Posner jjposner at snet.net
Sun Mar 15 18:39:43 CET 2009


(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





More information about the Python-list mailing list