Difference Between Python Class & Instance Attributes

In this article we are going to talk about Difference Between Python Class & Instance Attributes,

so first of all let’s talk about Python Instance Attributes.

 

 

What is Python Instance Attribute ?

Python instance attribute is a 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.

 

In this example the name and email are instance attributes, because it is in the init()

method, and these variables are unique to each object. you can see that we have created

two objects of Student class, and the instance variables are unique for each object,

if you change one of them , there will be no affect in the other object.

 

 

Run the code and this will be the result.

Difference Between Python Class & Instance Attributes
Difference Between Python Class & Instance Attributes

 

 

 

 

What is Python Class Attribute ?

Python class attribute is a 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.

 

in above examples the age 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.

 

Leave a Comment