Class and instance attributes
A class is a code template for creating objects. Objects have member variables and have behavior associated with them. In python a class is created by the keyword class. An object is created using the constructor of the class.
What’s a class attribute:
Class attributes are attributes that 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.
There For an instance attribute:
A variable belonging to one, and only one, object and it is defined inside the constructor function of a class. So, every object has its own copy of the instance attribute.
How to create them:
Class attributes:
There are many ways to create them: we can create an empty class and then create the attribute like this:
or create it along with the class:
and That’s the Pythonic way to do it.
or you can create it in the __init__() which is used to initialize the object’s state by using the class name.
or using __init__() with cls with is short for class.
Instance attributes:
you can create it after the class is created.
or create it along with the __init__() using self.
or with descriptors.
which is the Python way.
What are the differences between them:
- Class Attributes can mutate to be instance attributes not the other way around.
- Class attributes are shared by all instances. However, instance attributes only can be found in that particular instance.
__dict__ :
Python stores attribute in a dictionary using its plus side. Dictionaries can store every type of data. So it’s easier to access every attribute and its value whether it’s an integer, a list, or a Function.