How object and class attributes work
What’s a class attribute:
Class attributes are variables of a class that are shared between all of its instances. They differ from instance attributes in that instance attributes are owned by one specific instance of the class only, and are not shared between instances. This is highlighted in the illustration below.
Instance attribute:
An instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function,
__init__(self,..)
of the class.A class attribute is a Python variable that belongs to a class rather than a particular object. It is shared between all the objects of this class and it is defined outside the constructor function,
__init__(self,...)
, of the class.Class attributes are the variables defined directly in the class that are shared by all objects of the class.
Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor.
The following table lists the difference between class attribute and instance attribute:
What’s an instance attribute and the ways to create them?
Instance attributes are owned by the specific instances of a class. This means for two different instances the instance attributes are usually different. If we have two instances and we want to change a class attribute, you have to do it with the notation ClassName.AttributeName. Otherwise, you will create a new instance variable.