Class and Instance Attributes in Python

In this tutorial, we are going to learn about Class and Instance Attributes in Python with some easy examples.

This tutorial helps in understanding other concepts of class and object in Python easily.

As Python supports Object-oriented programming, most of the things in Python programs is an object having some methods as well as properties.

The classes and objects contain some attributes with which we will deal in this tutorial.

Python – Class and Instance attributes

Before starting first of all let us know about attribute:

Attribute: In programming terms, an attribute can be defined as something[usually variables] that defines a property of an object or element, etc..

Class Attributes:

Class Attributes are the Python variables that belong only to a particular class. The objects which belong to the same class can share class attributes.

Usually, we write these class attributes inside the class i.e inside the body of a class.

Example:

#Python code to demonstrate class attributes in python
>>> class example:
...   a = "code speedy"
... 
>>> x = example()
>>> y = example()
>>> print(x.a)
>>> print(y.a)
>>> print(example.a)

Output:

Class and Instance Attributes in Python

As seen above for the class “example” we have created the instances x,y and when we print the attribute for these instances it is the same i.e “a” hence, both displayed “code speedy”.

Instance Attributes:

These are Python variables that belong to a particular instance i.e unlike class attributes these are not shared by other instances each instance i.e each object has its own attribute.

NOTE:

We usually use a dictionary object to store object attributes and hence, we display the object attributes in the form of a dictionary.

Example:

#Python code to demonstrate instance attributes

>>> class intern:
...   def __init__(self,username,password):
...      self.__username = username
...      self.__password = password
...
>>> a = intern("abc",  123)
>>> a.__dict__

>>> b = intern("def",  456)
>>> b.__dict__

Output:

Class and Instance Attributes in Python

Finally, I hope this tutorial helped you all !!

You can also learn:

Leave a Reply

Your email address will not be published. Required fields are marked *