Class initialization

Benjamin Kaplan benjamin.kaplan at case.edu
Sun Aug 8 18:57:59 CEST 2010


On Sun, Aug 8, 2010 at 6:32 AM, Costin Gament <costin.gament at gmail.com> wrote:
>
> Hi there.
> I'm kind of a beginner with Python (and programming in general). My
> problem is with initializing a class. Let's say I've defined it like
> this:
>
> class foo:
>   a = 0
>   b = 0
>
> and later I'm trying to initialize two different classes like this:
> c1 = foo()
> c2 = foo()
>
> The problem I have is that c1 and c2 tend to point to the same
> instance, like a weird c-like pointer. Please tell me, what am I doing
> wrong?
>
> Thank you,


Python is not C++ or Java. Don't expect it to behave like them. In
Python, everything you declare in the class namespace is in the
*class* namespace. Since functions are objects too, this works out
rather nicely for the most part. Where it doesn't work is when you use
mutable variables.

Here's the example you wanted to give:

class Foo(object):
    a = []
    b= []


Unlike Java or C++, classes are objects too. That leads to one of the
neat tricks you can do with Python. The code above is exactly the same
thing as this

Foo = type("Foo",object, {}) #that dictionary will become Foo's list
of attributes
Foo.a = []
Foo.b = []

Now, when you call f1 = Foo(), it creates a new object. But here's
what happens when you call f1.a.append(1) :

* First, Python will look in the attributes of f1 for a. But f1
doesn't have an attribute "a".
* So it starts looking up the classes in the inheritance tree. It
looks at Foo and finds that Foo does have an attribute "a", so it
grabs that.
* Then, it looks up the attribute "append" on the a attribute (which
is a list), and calls that with the arguments Foo.a and 1.
* When f2 = Foo() goes looking for a, it finds the exact same object-
Foo.a. It doesn't have its own copy,

If you want an object to have its own copy of the variable, you have
to create the new copy when the object is created, not when the class
is created. That's why you'll see this in most Python programs :

class Foo(object) :
    def __init__(self) : #self is the new object that was just created.
       #now here we'll assign the attributes on the new object,
instead of the class.
       self.a = []
       self.b = []



More information about the Python-list mailing list