Python Tutorial
About Lesson

In this lesson we want to learn about Python Class Attributes VS Instance Attributes, and also we are going to create a practical example for this, so now let’s define these two concepts(Python Class Attributes & Python Instance Attributes).

 

Python object has two types of attributes: Class Attribute and Instance Attribute.

 

 

Instance Attribute 

An instance attribute is a Python variable belonging to only one object. This variable is only accessible in the scope of this object and it is defined inside the init() method also Instance Attributes are unique to each object.

 

 

Now let’s create a practical example, you can see that in this code i have created two variables, these two variables are called instance attributes, because they are belonging to only one object and it is defined inside the init() method. also these attributes are unique to each object.

 

 

 

Run the code and this is the result.

Python Class Attributes VS Instance Attributes
Python Class Attributes VS Instance Attributes

 

 

 

Class Attribute 

A class attribute is a Python variable that is owned by a class rather than a particular object. It is shared between all the objects of this class and it is defined outside the initializer method of the class.

 

 

OK now let’s add a class attributes in our example, you can see that in this example the email is a class attributes, because that is owned by a class rather than a particular object.

 

 

 

Difference Between Class & Instance Attributes 

What is difference between instance and class attributes ? instance attributes are unique to each object, but class attributes are not unique, if you change the class attribute it will affect all instances of the class. in above examples the email is a class attribute and it belongs to the class, it is shared by all instances. When you change the value of a class attribute, it will affect all instances that share the same exact value. the variable name and age are instance variable, because they are unique to the instance, if you change one instance variable, the second instance variable will not be affected. but in class attribute when you change the variable, it will affect all the instances.