Class initialization

Mel mwilson at the-wire.com
Mon Aug 9 01:47:18 CEST 2010


Costin Gament wrote:

> So you're saying I should just use __init__? Will that get me out of
> my predicament?
> No, I don't quite understand the difference between my exemple and
> using __init__, but I will read the docs about it.

Here's the thing about class variables:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class AClass (object):
...   var = 5
... 
>>> a = AClass()
>>> b = AClass()
>>> a.var, b.var
(5, 5)
>>> AClass.var = 7
>>> a.var, b.var
(7, 7)
>>> a.var = 9
>>> a.var, b.var
(9, 7)
>>> a.var is AClass.var
False
>>> b.var is AClass.var
True

When `var` is defined as a variable in AClass, it belongs to AClass.  But 
all the instances of AClass are allowed to access it as though it's their 
own -- it's a sensible way for Python to manage attribute lookup.

Assigning to AClass.var changes the value as seen by all the instances.

Assigning to a.var creates a new variable in instance a's namespace, and 
from then on that becomes the value that will be found by looking up a.var .  
The `is` test shows that this is true.

	Mel.





More information about the Python-list mailing list