Puzzled by behaviour of class with empty constructor

Diez B. Roggisch deets at nospam.web.de
Fri Jan 25 17:53:59 EST 2008


dbaston at gmail.com schrieb:
> 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?

It's simple - you didn't create an instance-variable, but instead a 
class-variable.

You need to do this:

class Axis:

    def __init__(self):
        self.ends = []


Diez



More information about the Python-list mailing list