1

Possible Duplicate:
Python: Difference between class and instance attributes

At work today, I spent about three hours with pdb trying to figure out why a dictionary on an object wasn't holding the correct values.

This is a nice template for what was happening:

class A:
    prop = {}
    def __init__(self, test):
        temp = self.method(test)

        for i in temp.keys():
            self.prop[i] = temp[i]

    def method(self, test):
        return ({ 'x': test, 'y': test })

a = A(3)
b = A(4)

print a.prop
print b.prop

will return

{'y': 4, 'x': 4}
{'y': 4, 'x': 4}

I've attributed the problem to line two. I checked the memory location of both a.prop and b.prop, and they were the same.

Because it's instantiated in the class, outside of the initializer/constructor, it allocates new space for each property, but allocates the new space for prop, and stores the same memory location in it. So, every other property on a and b were correct (different), except the ones that were defined as objects.

Is this expected behavior? I Know this is how it would work in say something like C++ (because at that point, they're kinda-static, right?).

Can someone explain to me why python treats it this way? Are there specific applications for it, when you could otherwise specify it static?

Community
  • 1
  • 1
Travis
  • 250
  • 1
  • 2
  • 9
  • 7
    Rather than think about the memory management, you should think about the objects. A class attribute is a single object shared among all instances; an instance attribute is an object per instance. The reason Python treats it this way is that class attributes and instance attributes are two different things, for two different purposes (storing info on the class or on the instance). It's not a memory management detail, it's a real semantic difference. – BrenBarn Nov 02 '12 at 20:02

0 Answers0