Object-oriented programming is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields, and code, in the form of procedures.

Python being OOP language allows us to create and use class and objects.

With class and objects, we will be able to explore all the features of OOP i.e

  • Inheritance
  • Encapsulation
  • Polymorphism

Let’s see what is class and objects in Python with examples.

What is a Class in Python?

The class is a blueprint used for creating objects.

An object is the instance of a class.

Let’s understand this with a real-world example.

Suppose in a class there are 60 students. Each student has its own roll no, name and date of birth. Everyone in the class is a student, what makes them unique is their roll no, name and dob which is also known as attributes.

So here Student is a class and every individual person with unique attributes is an object.

Let’s make this more clear by implementing it in python.

Example 1: Python Class and Object

Explanation

Recommended:

First, we have created a ‘Student’ class using the ‘class’ keyword. In the class, we have declared two methods using the ‘def’ keyword.

  • __init__ : It is a predefined method in python (name fixed). It is similar to the constructor of Java or C++. It is called at very first and only for one time when we create an object of the same class. We usually use it to initialize the attributes of the objects, therefore it is necessary to pass all the value of at the time of object creation (We have done the same in above program).
  • display : We have explicitly declared this function to display all the attributes/details of the objects.

we have declared self parameter to every methods to make it instance methods. It means that we can only call these methods using an object (similar to what we have done in our program). Also, we don’t require to explicitly pass the value for self during the function call. Python automatically does itself.

Example 2: Python Class and Class Method

Explanation

Almost everything in this program is similar to Example 1. We have only introduced an extra method in the class.

The new method is a class method. ‘@classmethod‘ decorator is used to make any method a class method.

A class method is a method that can also be accessed directly by class name without an object (like in the above example).

cls‘ is nothing but ‘self‘ name changed. It is usually named like this for every class method (Just a naming convention). Python automatically detects the method as a class method because of ‘@classmethod’ decorator and passes appropriate value/object to it, so that it behaves like a class method.

I hope you have understood something about class and objects in python. If you have any doubt then comment below.

Leave a Reply

Close Menu