Python Object-Oriented with examples

Python Object Oriented
Python Object Oriented

Python is High-level Programming language as well as supports the Object-Oriented Programming. In Python, we can work with classes, objects and others features of OOPs. In this article, we will discuss the concept of Python Object-Oriented programming with examples.

Python Object-Oriented Programming

Python Object-Oriented
Python Object-Oriented

Object-oriented programming is a model for programming languages. This model gives various concepts to improve the programming techniques. The model works on the principle of to define the logic and not the data.

Features of Object-Oriented Programming:


This feature of OOPs is to bind data and logic together. This feature is achieved with the help of classes. When we use the OOPs model to create a program we have to use class. In class, we have to include methods and variable.

Data Abstraction

The Data abstraction means hiding the logic behind the code. This feature implements the security for the business logic.  We can achieve with the help of objects and classes. There are also access specifiers that we can allocate to the member function, instance variable to restrict authorization.


Inheritance is one of the features of OOP which is widely implemented. With inheritance in programming provides reusability. We can use the existing class to a new one. The new class we create will have the feature of the old class as well of its own.


Polymorphism means more than one form. In OOP, we can perform multiple actions under one name. We can achieve this with the help of method overriding and operator overriding.

Message Passing

In a single program, we can have multiple classes. We can pass data between the class to share them. This sharing of data and passing among the class is known as message passing.

Terminologies in Object-Oriented Programming

When start programming using OOP, there are some terms we need to know. These words come into the program many times, and they are as follow.


The class is the primary element of OOP. We cannot implement the model without the class. In the class, we group the variable and methods.


We have to create the objects of the class to access the members of the class. An object can be said as a variable of the class.

Class Member

The variables and the methods of the class together are the class members.


The method is not a new word and is also an important part of OOP. We use the method to implement the logic. To achieve different operation, we can use the method in the class.


Instantiation means creating an instance of the class. Object helps to create the instance of the class.

Method Overloading

In method overloading, we create multiple methods of the same name. Here each method can perform different actions. We can achieve compile time polymorphism through overloading of the method.

Method Overriding

Method overriding means run-time polymorphism. In overriding, we have multiple methods of the same name. When we call the method at the run time the interpreter decides which method to call.

Operator Overloading

Not only method but also we can overload an operator. We can provide more than one function to an operator that is known as operator overloading.

Classes and Objects

After an overview on OOP let us discuss how to implement them. To implement Python Object-Oriented, we have to create the class and objects.

Create a Class

To create a class in Python, we have to follow below syntax.


class class_name:
 #body of the class

We have to use the class keyword to create the class. After the keyword, we have to specify the name of the class. The name of the class can be any valid Python identifier.

The class keyword and name of the class together are the header of the class. After the header, we have to define the body of the class.

In the body of the class, we represent the class members. The class members can be the variables and methods.


class student:
 def name(self):
 print("Enter your details")
 student.fname=input("Your first Name:")
 student.lname=input("Your last name:")

 def display(self):
 print('First name:',student.fname)
 print('Last name:',student.lname)

Create an object of Class

After creating the class, we have to create the object to access the members of the class. To create the object we have to follow the below syntax.



The name of the object can be any valid Python Identifier. We can create the object of the class of which we create. The instance of the class can access the member of their respective class only.


s1 = student()

Here, we have created the object of the class student. After creating the object, we will access the member of the class. To access the class member, we have to follow the below Syntax.



Here the class member name can be the name of the method or name of the variable.


#accessing class variables

#acessing class methods


Enter your details
Your first Name:xyz
Your last name:abc
First name: xyz
Last name: abc

Defining Method in Class

In Python Object-Oriented Programming, we can define a method in the class to perform some tasks. To define a function in the class, we have to follow below syntax.


def method_name(self,arg1,arg2...,argN):
 #body of the method

To create the method in the class, we have to use the def keyword. After the def keyword, we have to specify the name of the method.

We must remember one thing; the constructor cannot be called explicitly. In the constructor, we can pass as many arguments we need. But there is one argument we must have to give, i.e., self. If we do not w the keyword, we will get an error.


class student:
 def display(self,val1):
  print("I am from class student")
  print("Value of parameter is",val1)

s1 = student()


I am from class student
Value of parameter is t4tutorial

In the example, we have a class student. The class has method display(). We have to pass a value to the method. When we create the method display(), we also have to give the variable self.

Constructor of a class

In Python Object-Oriented Programming, another property of the class is the constructor. The constructor of the class is a method that is called automatically. In any other programming language, we create a constructor using the class name.

But in Python, we can create a class constructor using the method __init__(self). The primary use of the constructor is value initialization. We can use the constructor of the class to perform some operations when the object of the class is created.

Syntax for constructor

def __init__(self,val1,val2):
 #body of the constructor


class student:
 def __init__(self,val1,val2):

s1 = student("Abc","xyz")



Built-in Class attribute

In Python Object-Oriented programming, the class has following built-in attributes.

__doc__: This attribute contains the documentation. If there is no documentation given in the class, it will return None.

__dict__: This attribute of the class is a dictionary which maintains the namespace.

__name_: It is the name of the class.

__module__: It will be the name of the modules of the class.

__bases__: If there is inheritance than the class the __bases__ is a tuple. The tuple will have the record of the base class.


class student:
 def display(self,val1):
 print("I am from class student")
 print("Value of parameter is",val1)

print('Name of the class',student.__name__)
print('Class Doccumentation',student.__doc__)
print('Class Ditcionary',student.__dict__)
print('Class Bases',student.__bases__)
print('Class Bases',student.__module__)


Name of the class student
Class Doccumentation None
Class Ditcionary {'__module__': '__main__', '__weakref__': <attribute '__weakref__' of '
student' objects>, '__dict__': <attribute '__dict__' of 'student' objects>, 'display': 
<function student.display at 0x00000000036DBB70>, '__doc__': None}
Class Bases (<class 'object'>,)
Class Bases __main__

Built-in Method to access class attributes

We can access attributes of the class with dot operator. There are also built-in methods to access the attributes of the class. In Python, we have following methods to access the properties of the class.

1. getattr(obj, name[, default]) :

It will give the attribute of an object. In the method, we have to pass the object name and the name of the attribute.

2.hasattr(obj,name) :

We can use this method if we want to check that an attribute in an object exists or not. It will return true if the attribute exists else false.

3. setattr(obj,name,value) :

This method will set an attribute of an object. In the method, we have to pass the object, name of attribute and value of the attribute.

4. delattr(obj, name) :

This method will delete an attribute of the object.


class student:
 def display(self):
 print("I am from class student")
 print("Value of Attribute is",val1)


#Get attribute
print("Get the attribute",getattr(s1,'val1'))

#check attribute
print("Check the attribute",hasattr(s1,'val1'))

#set attribute

#check attribute val2
print("Check the attribute",hasattr(s1,'val2'))
#Get attribute
print("Get the attribute of val2",getattr(s1,'val2'))

#delete the attribute


Get the attribute 20
Check the attribute True
Check the attribute True
Get the attribute of val2 30

Destroy objects

In Python Object-Oriented programming we can also delete an object of the class. Removing the object will free the occupied memory by the object.

Python automatically clears the processor to free the space. Python performs garbage collection that is, it will reclaim the memory over some period automatically.

But we want to remove the object explicitly then it is possible. To do so, we have to the __del__() destructor. We cannot call the __del__() destructor explicitly because the python interpreter will invoke it implicitly.

When we use the del operator to remove the object, the Python interpreter will call the __del__() method.

Once we remove the object, we cannot access the members of the class with that object. 

Syntax to delete the object

def __del__(self):
 #body of the destructor


class student:
 def display(self):
 print("I am from class student")
 print("Value of Attribute is",self.val1)

 def __del__(self):
 print("Object Deleted",self.__class__.__name__)
print("\nAfter Deleting the object")


I am from class student
Value of Attribute is 20
Object Deleted student

After Deleting the object
Traceback (most recent call last):
 File "E:\Programs\Python 3\", line 13, in <module>
NameError: name 's1' is not defined

Inheritance of Class

The Python Object-oriented programming also supports the Inheritance. The Inheritance the feature of OOPs concept. It provides the programmer to create a new class from an existing class. Inheritance in Python Object-oriented gives the idea of reusability.

The new class that we create from the existing class is known as subclass or child class. The class from which we extend an another class is known as a super class or Parent class.

The child class will have the property of the parent class. With the object of the subclass, we can access the members of the subclass as well as super class.

We have to follow the below Syntax for inheritance.


 class subClass_name(parent_class1,parent_class2,...parent_classN):
   #body of the class

In above syntax, we will declare the subclass like the regular class. In the header of the subclass, we have to use the class keyword and give the name of the class.

After the name of the class, we have to provide the name of the class or classes which we want to inherit. In the braces, we can pass as many class we want.

Once we have inherited the super class into the subclass, we have to create the object of the subclass.

In Python Object-oriented programming, we must remember two points while working with inheritance in Python.

  1. The object of the subclass can access the member of the subclass as well as the members of the parent class.
  2. The object of the parent class cannot access the member of the class.


 class student:
 def details(self):
 self.roll_no=input("Enter Roll No:")"Enter Name:")

class marks:
 def gmark(self):
 self.mark1=input("Enter Mark1:")
 self.mark2=input("Enter Mark2:")
 def dmark(self):
class data(student,marks):
 def display(self):
 print("Roll No:",self.roll_no)
#create the object of sub class

#access the member of super class
d1.details() #class student
d1.gmark() #class marks

#access the member of the same class

d1.dmark() #class marks

In above example, we have represented the inheritance. We have subclass name data. The class data has two super class student and mark.

We have inherited both the class in the class data. After creating the object of core data, we can access the class members of all the three class.


Enter Roll No: A
Enter Name: t4tutorial
Enter Mark1: 20
Enter Mark2: 30
Roll No: A
Name: t4tutorial
Mark1: 20
Mark2: 30

Check Relationship in Inheritance

In Python Object-oriented programming, we can also test the relationship between the classes and object. Also, we can verify the relationship between subclass and super class. For testing the relationship, we have following methods.


This method will test the relationship between classes. In the class, we have to pass the name of the superclass and subclass. If there is a relationship, it will return true else false.


class example:
 def __init__(self):
 print(" I am from example")

class example1(example):
 def __init__(self):
 print("I am from Example 2")

m1 = example1()


I am from Example 2


This method will check the relationship between object and class.It is a boolean function. Thus it returns true or false. If the given object is the instance of the class, it will return true else false.


class example:
 def __init__(self):
 print(" I am from example")

m1 = example()


 I am from example

Method Overriding

In Python Object-oriented programming, we can override method. Overriding of the method takes place in Inheritance of classes.

We can redefine a method in the subclass which already has some definition in the parent class. The overriding provide polymorphism in Python. With the help of overriding, we can perform multiple functions under a single name.

To override a method in the subclass, we have to create a new function. The name of the new method should be same as the name of the super class.

When we create an object of the base class and try to call the method of the super class, the Python interpreter will provide the method of the subclass only because it is overridden.


class maths:
 def add(self,n1,n2):

class solve(maths):
 def add(self,n1,n2):

Here in above example we have two classes maths and solve. The class solve inherits the class maths. Thus the object of the class can inherit the property of maths.

We have a method add() in both the classes. The method of class solve overrides the method of the class maths. So when executing the code, we get Below’s output.


N1: 3 
N2: 4
N1*N2: 12

Operator Overloading

In Python Object-Oriented Programming, we can overload the basic operators of Python. The operators can perform more actions than their regular actions.

To overload method, we have different methods they are as follow.

OperatorOverloading Method
 Floor Division__floordiv__()
 Bitwise Left Shift__lshift__()
Bitwise Right Shift__rshift__()
Bitwise AND__and__()
Bitwise OR__or__()
Bitwise XOR__xor__()
Bitwise NOT__invert__()


class overload:
 def __init__(self, n1, n2):
 self.n1 = n1
 self.n2 = n2

 def __str__(self):
 return 'Overload (%d, %d)' % (self.n1, self.n2)
 def __add__(self,other):
 return overload(self.n1 + other.n1, self.n2 + other.n2)

o1= overload(4,30)
o2 = overload(-23,4)

In above example we are overloading the addition operator. Normally the plus operator performs addtion on number or concate the strings. But we can overload it and perfrom addition between the objects. There is a constructor to intialize the value.

Each time when we create the object and pass the value the variable will be assigned the values. When we execute the above code we get the following output.


Overload (-19, 34)

Python Data Hiding

Data Security is the most important priority to the user. In Python Object-Oriented programming, we can also provide security to data.

We use the object to access the class members. There are no access specifiers in Python to provide the security to data. In order to make the member of the class, we have to use underscore.

The member of the class which you want to hide from unwanted access, we have to put double underscore with the name of the member at the starting.


class maths:
 def add(self):


In above code, we have class maths which has Four class members. There are three variables n1, n2, n3. The n1 and n2 variables are regular variables.

But the n3 is protected as there are two underscores before the name of n3. We can access the n3 variable only in the maths class. When we execute the above code we get this output.


N1: 20 
N2: 40
Traceback (most recent call last):
 File "E:\Programs\Python 3\", line 13, in <module>
AttributeError: 'maths' object has no attribute '__n3'

Here we will conclude the topic of Python Object-oriented Programming. If there are any questions feel free to ask in comments below.