Puzzled by behaviour of class with empty constructor

Tomek Paczkowski oinopion at gmail.com
Fri Jan 25 17:52:22 EST 2008


dbaston at gmail.com wrote:

> Hello,
> 
> I have a class called 'Axis' that I use as a base class for several
> types of axes that can be created by a grid generation program that I
> have written: equally-spaced grids, logarithmic grids, etc.  In any
> case, if I use this base class by itself, I see some puzzling
> behaviour:
> #############
> class Axis:
>     ends = []
>     N = None
>     def __init__(self):
>         pass
> 
> x = Axis()
> y = Axis()
> z = Axis()
> 
> x.ends.append((0,2))
> 
> print x.ends,y.ends,z.ends
> #############
> Running the following code outputs:
>>>> [(0, 2)] [(0, 2)] [(0, 2)]
> 
> Can anyone explain this?

Well, you are using a class variable - Axis.ends. It's shared among all
instances of Axis class. To have it separate setup it in __init__ like:

class Axix:
    def __init__(self):
        self.ends = []
        self.N = None

You see, code inside class, but outside methods is executed only once and
any variables are then linked with class, and not instances (more/less).
Take look at: http://docs.python.org/tut/node11.html

   ~TomekP

-- 
Someone whom you reject today, will reject you tomorrow.




More information about the Python-list mailing list