Object oriented programming python

By: On:

In this Python tutorial, we will discuss object oriented programming python, we will learn the concept with the help of examples.

  • Object Oriented Programming in python
  • What are Python OOPs concepts
  • Create a class in python
  • Instance Attribute in python
  • Class Attribute in python
  • Create an object in python
  • The init function in python
  • Method in python
  • Self Parameter in python
  • Create an object and class in python
  • Python modify object properties
  • Inheritance in python
  • Types of Inheritance in Python
  • Method Overriding in python
  • Method Overloading in python
  • Polymorphism in Python
  • Encapsulation in python
  • Abstraction in Python

Object Oriented Programming in Python

Python is an object-oriented programming language and it supports different programming approaches one of the approaches is by creating “objects” which mean we can solve a problem in python by creating objects in our programs.


In python, we can easily create and use classes and objects, and also it focuses on writing the reusable code.

What are Python OOPs concepts

Python object-oriented programming (OOPs) concepts include class, object, methods, etc along with OOPs features such as inheritance, polymorphism, Encapsulation, and data abstraction.

Create a class in python

A class is a blueprint for the object, to create a class we will use the class keyword and from the class, we construct instances.

Example:


class student:
roll = 1
print(student)

After writing the above code (create a class in Python), Ones you will print “ student ” then the output will appear as a “<class ‘__main__.student’> ”. Here, the class is the keyword and the class name is “student”.

You can refer to the below screenshot create a class in python.

object oriented programming python
Create a class in python

Create an object in python

Let us see how to create an object in Python.

In python, an object is a real-world entity that has its state and behavior, everything in python is an object. To create an object we can use the class name.

Example:

class student:
roll = 1
a1 = student()
print(a1.roll)

After writing the above code (create an object in python), Ones you will print “ a1.roll ” then the output will appear as a “ 1 ”. Here, the class name is “student” and we create the object “a1” of class student and we will print the value of roll.

You can refer to the below screenshot create an object in python.

python 3 object-oriented programming
Create an object in python

Instance Attribute in python

In python, instance attribute is an attribute or properties which is attached to an instance of the class. The instance is accessed by using the dot notation.

Example:

class teacher:
def __init__(self):
self.name="John"
self.salary=100000
t1=teacher()
print(t1.name)
print(t1.salary)
  • After writing the above code (instance attribute in python), Ones you will print “ t1.name t1.salary ” then the output will appear as a “ John 100000 ”. Here, the instance attributes are defined by name and salary in the constructor.
  • The instance attribute is accessed by dot notation t1 is instance name and .name is the attribute name.

You can refer to the below screenshot instance attribute in python.

object-oriented programming python
Instance Attribute in python

Class Attribute in python

A class attribute is an attribute whose value remains the same for all instances of a class is known as a class attribute. It is defined at a class level rather than inside the method. The value of the class attribute is shared by all objects.

Example:

class teacher:
value = "Welcome"
print(teacher.value)

After writing the above code (class attribute in python), Ones you will print “ teacher.value ” then the output will appear as a “ Welcome ”. Here, the attributes are accessed by using the class name which is “teacher” and the class attributes “.value”.

You can refer to the below screenshot class attribute in python

python object oriented programming
Class Attribute in python

The init function in python

In python, __init__() is a built-in function, and all the classes have a function called init which is always executed when the class is initiated. We use the __init__() to assign the values to object properties.

Example:

class student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
a1 = student("Eelon", 24)
print(a1.name)
print(a1.roll)

After writing the above code (the init function in python), if you will print “ a1.name a1.roll ” then the output will appear as an “ Eelon 24 ”. Here, the class name is “student” and we use the init function to assign values name and roll and then the value gets printed.

You can refer to the below screenshot the init function in python.

The init function in python
The init function in python

Method in python

The method in python is similar to a function, a method is functions defined inside the body of a class and it is used to define the behavior of an object.

Example:

class student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def function(self):
print("Welcome to python " + self.name)
a1 = student("Elon", 24)
a1.function()
  • After writing the above code (method in python), if you will print “ a1.function() ” then the output will appear as a “ Welcome to python Elon”.
  • Here, the class name is “student” and we use the init function to assign values name and roll, here my instance method is “function()” and it is called instance method because it is called on instance object “a1”.

You can refer to the below screenshot method in python.

Method in python
Method in python

Self Parameter in python

The self parameter is used to reference the current instance of a class, also by using “self” we can access the attributes and method of a class in python. We can use another parameter name instead of a “self” but it should be first parameter of any function in class.

Example:

class student:
def __init__(newobj, name, roll):
newobj.name = name
newobj.roll = roll
def function(newobj):
print("Welcome to python " + newobj.name)
a1 = student("Elon", 24)
a1.function()

After writing the above code (self parameter in python), if you will print “ a1.function() ” then the output will appear as an “ Welcome to python Eelon ”. Here, we use the word “newobj” instead of self and still we get the same result.

You can refer to the below screenshot self parameter in python.

Self Parameter in python
Self Parameter in python

Create an object and class in python

A class is a collection of objects or we can say it is a blueprint of objects which has common behavior and attributes. The object is an instance of the class which has state and behavior.

Example:

class teacher():
def __init__(self,name,id,salary):
self.name = name
self.id = id
self.salary = salary
obj1 = teacher("Simon",101,12500)
print(obj1.__dict__) 
  • After writing the above code (creating object and class in python), if you will print “ obj1.__dict__() ” then the output will appear as a “ {‘name’: ‘Simon’, ‘id’: 101, ‘salary’: 12500} ”.
  • Here, ‘obj1’ are objects which are instantiated against the class ‘teacher’. The word ‘__dict__’ is a dictionary that prints all the value of the object with the given parameter.

You can refer to the below screenshot for creating object and class in python.

Create an object and class in python
Create an object and class in python

Python modify object properties

In python, you can modify the properties of an object. Here, we will modify the “roll”.

Example:

class student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def function(self):
print("Welcome to python " + self.name)
a1 = student("Elon", 24)
a1.roll = 30
print(a1.roll)

After writing the above code (python modify object properties), if you will print “ a1.roll() ” then the output will appear as an “ 30 ”. Here, it will modify the roll and we need to set the roll of a1 to 30 and it will print the modified result.

You can refer to the below screenshot python modify object properties.

Python modify object properties
Python modify object properties

Inheritance in python

Let us try to understand inheritance in Python with an example.

Inheritance is the process in which class inherits all the properties and methods from another class. The new class is called derived class or child class and the one from which it derived is called parent class or base class.

Example:

class Teacher():
def myfirst(self):
print('This is my first function')
class Child(Teacher):
def mysecond(self):
print('This is my second function')
obj = Child()
obj.myfirst()
obj.mysecond()

After writing the above code (inheritance in python), if you will print then the output will appear as an “ This is my first function This is my second function”. Here, you can access the parent class function using the child class object.

You can refer to the below screenshot inheritance in python.

Inheritance in python
Inheritance in python

Types of Inheritance in Python

Types of inheritance depends upon the number of child and parent class involved. There are four types of inheritance in python.

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Single Inheritance

In single inheritance child class inherits only a single parent class.

Example:

class Teacher():
def myfirst1(self):
print('This is my first function')
class Child(Teacher):
def mysecond2(self):
print('This is my second function')
obj = Child()
obj.myfirst1()
obj.mysecond2()

After writing the above code (single inheritance), if you will print then the output will appear as a “ This is my first function This is my second function”. Here, you can access the parent class function using the child class object and child class inherits the property of a single parent class.

You can refer to the below screenshot single inheritance in python.

Single Inheritance
Single Inheritance

Multiple Inheritance

In multiple inheritance a child class inherits from more than one parent class.

Example:

class Teacher1:
def myfirst1(self):
print('This is my first function')
class Teacher2:
def mysecond2(self):
print('This is my second function')
class Child(Teacher1,Teacher2):
def mythird3(self):
print('This is my third function')
obj = Child()
obj.myfirst1()
obj.mysecond2()
obj.mythird3()
  • After writing the above code (multiple inheritances), if you will print then the output will appear as a “ This is my first function This is my second function This is my third function”.
  • Here, you can inherit both parent class function using the child class object and the child class inherits the property of multiple parent class.

You can refer to the below screenshot multiple inheritance in python.

Multiple Inheritance
Multiple Inheritance

Multilevel Inheritance

In multilevel inheritance child class becomes a parent class for another child class

Example:

class Teacher:
def myfirst1(self):
print('This is my first function')
class Child(Teacher):
def mysecond2(self):
print('This is my second function')
class Child2(Child):
def mythird3(self):
print('This is my third function')
obj = child()
obj.myfirst1()
obj.mysecond2()
obj.mythird3()

After writing the above code (multilevel inheritances), if you will print then the output will appear as a “ This is my first function This is my second function This is my third function”. Here, the child class act as a parent class for another child class.

You can refer to the below screenshot multilevel inheritance in python.

Multilevel Inheritance
Multilevel Inheritance

Hierarchical Inheritance

In hierarchical inheritance more than one derive class to inherit properties from parent class.

Example:

class Teacher:
def myfirst1(self):
print('This is my first function')
class Child(Teacher):
def mysecond2(self):
print('This is my second function')
class Child2(Teacher):
def mythird3(self):
print('This is my third function')
obj = Child()
obj1 = Child2()
obj.myfirst1()
obj.mysecond2()
obj1.myfirst1()
obj1.mythird3()

After writing the above code (hierarchical inheritances), if you will print then the output will appear as a “ This is my first function This is my second function This is my first function This is my third function”. Here, we have a parent class and two child classes or derived class.

You can refer to the below screenshot hierarchical inheritance in python.

Hierarchical Inheritance
Hierarchical Inheritance

Hybrid Inheritance

Hybrid inheritance involve multiple type of inheritance taking place in a single program.

Example:

class Teacher:
def myfirst1(self):
print('This is my first function')
class Child(Teacher):
def mysecond2(self):
print('This is my second function')
class Child2(Teacher):
def mythird3(self):
print('This is my third function')
class Child3(Child,Teacher):
def myfourth4(self):
print('This is my fourth function')
obj = Child3()
obj.myfirst1()
obj.mysecond2()

After writing the above code (hybrid inheritances), if you will print then the output will appear as a “ This is my first function This is my second function “. Here, multiple inheritance taking place in a single program.

You can refer to the below screenshot hybrid inheritance in python.

Hybrid Inheritance
Hybrid Inheritance

Method Overriding in python

  • Python method overriding means creating two methods with the same name and the same number of parameters but the different print messages.
  • Here, the method overriding allows us to change or override the parent class function in the child class. Method overriding is an example of run time polymorphism.

Example:

class Teacher:
def new(self):
print("I am Teacher")
class Child(Teacher):
def new(self):
print("I am Child")
obj=Child()
obj.new()
  • After writing the above code (method overriding in python), if you will print then the output will appear as an “ I am Child .
  • Here, we created a teacher class that contains a new as method and message to print and also we created a child class that inherits from the teacher class which is parent class and it will override the message.

You can refer to the below screenshot method overriding in python.

Method Overriding in python
Method Overriding in python

Method Overloading in python

  • Python method overloading means we can have the same name but different arguments and a method can have one or more arguments.
  • Calling the same method in different ways is called method overloading in python. Method overloading is an example of compile-time polymorphism.

Example:

class Teacher:
def new(self, name=None):
if name is not None:
print('Welcome ' + name)
else: 
print('Welcome')
obj = Teacher()
obj.new()
obj.new('sam')
  • After writing the above code (method overloading in python), if you will print then the output will appear as a “ Welcome Welcome Sam .
  • We created a teacher class that contains a new() method. We first call the method obj.new() without any parameters and it prints “Welcome” and next time we call the same method with parameter value as “Sam” so we can call the new() method in two ways.

You can refer to the below screenshot for method overloading in python.

Method Overloading in python
Method Overloading in python

Polymorphism in Python

  • Polymorphism in Python means more than one form. Also, we can say it is a condition of occurrence in different forms.
  • Polymorphism is one of the important concepts in programming. For example, we know that the “+” operator is used for adding two integer numbers, and for the string, the same ” + ” operator is used for string concatenation.

Example:

val1 = 10
val2 = 20
print(val1+val2)
  • After writing the above code (polymorphism in python), if you will print then the output will appear as a “ 30 .
  • Here, the ” + “ operator is used for adding two integer numbers and here we will also see for string concatenation, so here the ” + “ operator can perform different operations for distinct data types.

You can refer to the below screenshot polymorphism in python.

Polymorphism in Python
Polymorphism in Python

Example:

string1 = "Welcome"
string2 = "Python Guides"
print(string1+" "+string2)
  • After writing the above code (polymorphism in python), if you will print then the output will appear as a “ Welcome Python Guides “.
  • Here, the ” + “ operator is used for concatenation of two string, so the ” + “ operator can perform different operations for distinct data types. In this way, polymorphism works.

You can refer to the below screenshot.

Polymorphism in Python
Polymorphism in Python

Encapsulation in python

  • Encapsulation is the process of wrapping up variables and methods into a single unit, it is the fundamental concepts of object-oriented programming in Python.
  • In python, though there is no explicit access modifier by using (__) double underscores we can make variable private.

Example:

class Teacher:
def __init__(self, name, salary):
self.name = name
self.__salary = salary
def disp(self):
print(self.name)
print(self.__salary)
teacher = Teacher('Suzan', 500000)
teacher.disp()
print(teacher.name)
print(teacher.__salary)
  • After writing the above code (encapsulation in python), if you will print then the output will appear as a “ Suzan 500000 .
  • Here, you can see that the variable can still be accessed by using the method which is part of a class and the private variable ” salary “.
  • It can’t be accessed directly from outside and will throw an error called ” Attribute Error “.

You can refer to the below screenshot encapsulation in python.

Encapsulation in python
Encapsulation in python

Abstraction in python

  • In python, abstraction is used for hiding the internal details and showing the functionalities. Abstraction means hiding the real implementation and knowing how to use it as a user and it is achieved by using abstract classes and interfaces.
  • An abstract class is a class that provides incomplete functionality and the interface provides the method names without method bodies.

Example:

from abc import ABC,abstractmethod
class teacher(ABC):
def teach_id(self, id, name, salary):
pass 
class child1(teacher):
def teach_id(self,id):
print("teach_id is 14520")
teach1 = child1()
teach1.teach_id(id)
  • After writing the above code (abstraction in python), if you will print then the output will appear as a “ teach_id is 14520.
  • Here, we have imported an abstract method and we have the parent and child class.
  • Also, the object is instantiated for the ‘child1’ and the functionality of abstract is used.

You can refer to the below screenshot abstraction in python.

Abstraction in python
Abstraction in python

You may like the following Python tutorials:

In this tutorial, we learned about Object-Oriented Programming in python and also we have seen how to use it with an example like:

  • Object-Oriented Programming in python
  • What are Python OOPs concepts
  • Create a class in python
  • Instance Attribute in python
  • Class Attribute in python
  • Create an object in python
  • The init function in python
  • Method in python
  • Self Parameter in python
  • Create an object and class in python
  • Python modify object properties
  • Inheritance in python
  • Types of Inheritance in Python
  • Method Overriding in python
  • Method Overloading in python
  • Polymorphism in Python
  • Encapsulation in python
  • Abstraction in Python

Leave a Comment