Style question - defining immutable class data members

Bruno Desthuilliers bdesth.quelquechose at
Sun Mar 15 21:06:58 CET 2009

John Posner a écrit :
> (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,

Becaause that's how you create instance attributes in Python. Why do you 
think 'self' - that is, a reference to some object - is mandatory in 
"methods" (really, functions) arguments list ?

Or do you mean that the existence of a synonym class attribute should be 
checked on each instance variable assignement ? This would probably be a 
big performance hit, and it would make per-instance method overloading 
impossible (remember that OOP is about objects, not classes).

More information about the Python-list mailing list