Yes, thatβs how it should work.
If a and b belong to an instance of Foo , then the correct way to do this is:
class Foo(object): def __init__(self): self.a = [] self.b = 2
The following makes a and b belong to the class itself, so all instances have the same variables:
class Foo(object): a = [] b = 2
When you mix two methods - as in the second example, this does not add anything useful and just causes confusion.
One point worth mentioning is that when you do the following in your first example:
foo.b = 5
you do not change Foo.b , you add a new attribute Foo , which is the "shadow" of Foo.b When you do this, neither bar.b nor Foo.b will change. If you subsequently execute del foo.b , this will remove this attribute, and Foo.b refers to Foo.b .
source share