Class attributes vs Instance attributes

Class attributes are attributes which are owned by the class itself . They will be shared by all the instances of the class. Therefore they have the same value for every instance . We define class attributes outside of all the methods, usually they are placed at the top, right below the class header. On the other hand, instance attributes are owned by the specific instances of a class. This means for two different instances the instance attributes are usually different. Instance variables are defined inside a method, normally __new__ or __init__ , and they are local to that instance. The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance.

Class Attributes

class a: list=[] y=a() x=a() x.list.append('a') y.list.append('b') x.list.append('c') y.list.append('d') print (x.list) print (y.list) output ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']

Instance Attributes

class a: def __init__(self): self.list = [] y=a() x=a() x.list.append('a') y.list.append('b') x.list.append('c') y.list.append('d') print (x.list) print (y.list) output ['a', 'c'] ['b', 'd']
In the examples above you can see, declaring the variables inside the class declaration makes them class members and not instance members. Declaring them inside the __init__ method makes sure that a new instance of the members is created alongside every new instance of the object.