#!/usr/bin/env python class B: b = 2 class C: a = B() def __init__(self): self.a.b = 1 c = C() c.a.b = 3 b = C() print c.a.b, b.a.b
Here, a is a class attribute of class C. That is, there exists only one such attribute for all objects of kind C. So the output of the print statement will be "1 1". This is the same as a static attribute in C++. But often I want an instance attribute. The correct way to do this would have been:
#!/usr/bin/env python class B: b = 2 class C: def __init__(self): self.a = B() self.a.b = 1 c = C() c.a.b = 3 b = C() print c.a.b, b.a.b
Now the output is "3 1", just as expected. I guess this all somehow makes sense in the Python world, but I tripped over this, and worst of all: Sometimes you don't even notice. If the class attribute is a simple type, like int, the first solution would have worked. However, I have not yet understood why that is the case. One more Python semantic that eluded me so far.