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?