Class and instance attributes
First of all, what is an attribute?
Put simple, attributes are the properties or the characteristic of an object.
To initialize an instance (an object), the __init__ function is used.
let’s start by creating a class called rectangle;
Now, let’s define the __init__ function, we’ll have width and height ass attributes of each object of the class Rectangle
width and height are called instance attributes, because they belong to the objects of the class. So each rectangle has his own width and height. They are protected. and they need a instance method getter and an instance method setter
Now what is class attribute?
While instance attributes are specific to each object, class attributes are the same for all instances. they are owned by the class itself. And are shared by all the objects(instances) of the class.
For example, let’s create a class attribute called number_of_instances;
Now we can access this attribute with any instance and they’ll all have the same value. For example, when adding a new object at the __init__ function, the number_of_instances variable gets incremented
Okay, Now that we have the two kinds, let’s review the differences,
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.
What is __dic__?
it’s a mapping object used to contain all the object in question’s attributes, each instance is stored in a dictionary. So basically, it’s an attribute that is a dictionary and contains all the other attributes, here’s an example:
Thank you for reading! =)