Style question - defining immutable class data members
Gary Herron
gherron at islandtraining.com
Mon Mar 16 01:10:46 EDT 2009
John Posner 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?
>
I wouldn't call it "silently" because "inst.x = ..." is quite explicit
about "x" being an attribute of "inst". The rules for creating a
variable are simple and very consistent.
Each of
Cls.x = ...
inst.x = ...
x = ...
will create a variable (if it does not already exist) in a class,
instance or local name space respectively.
Retrieving a value is more complex as Python may look through several
namespaces in succession to find a value: (For example, inst.x will
check the instance , then the class ...)
The problem here is that
inst.x += 1
is really
inst.x = inst.x+1
which according to those rules, (if inst.x is not yet defined)
has both an instance and a class reference in the same statement.
After that, x.inst is defined in the instance, so both sides refer to that.
Gary Herron
> Tx,
> John
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list