Magic class member variable initialization with lists

marek.rocki at wp.pl marek.rocki at wp.pl
Wed Nov 14 22:30:23 EST 2007


This is the expected behaviour. The reference on classes (http://
docs.python.org/ref/class.html) says:

> Variables defined in the class definition are class variables;
> they are shared by all instances. To define instance variables,
> they must be given a value in the __init__() method or in
> another method. Both class and instance variables are
> accessible through the notation ``self.name'', and an instance
> variable hides a class variable with the same name when
> accessed in this way.

In your example, 'a' is a class variable, so it's shared by all
instances. 'b' is also a class variable, but in the __init__ method
you create an instance variable with the same name 'b', which takes
precedence over the class-level variable, so 'b' isn't shared.

I think what you need is:

class Proof:
    def __init__(self):
        self.a = []
        self.b = []
        # other things

Regards,
Marek



More information about the Python-list mailing list