Python OOPs Concepts
Python OOPs Concepts
An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-world entities such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve the problem by creating
objects.
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.
2
In the above example, we have created the class named car, and it has two attributes
modelname and year. We have created a c1 object to access the class attribute. The c1 object
will allocate memory for these values.
Example program for both class and objects
3
Method
The method is a function that is associated with an object. In Python, a method is not unique
to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the
real-world concept of inheritance. It specifies that the child object acquires all the properties
and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph
means shape. By polymorphism, we understand that one task can be performed in different
ways. For example - you have a class animal, and all animals speak. But they speak
differently. Here, the "speak" behavior is polymorphic in a sense and depends on the animal.
So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs
and cats) have a concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict
access to methods and variables. In encapsulation, code and data are wrapped together within
a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects of
this class.
On the other hand, the object is the instance of a class. The process of creating an object can
be called instantiation.
5
In Python, we must notice that each class is associated with a documentation string which can
be accessed by using <class-name>.__doc__. A class contains a statement suite including
fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display(), which is used to display the information of
the Employee.
6
Here, the self is used as a reference variable, which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables.
We can use anything instead of self, but it must be the first parameter of any function which
belongs to the class.
The following example creates the instance of the class Employee defined in the above
example.
In the above code, we have created the Employee class which has two attributes named id
and name and assigned value to them. We can observe we have passed the self as parameter
in display function. It is used to refer to the same class attribute.
7
We have created a new instance object named emp. By using it, we can access the attributes
of the class.
It will through the Attribute error because we have deleted the object emp.
Python Inheritance
Inheritance provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class.
Single Inheritance:
In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.
8
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Example
9
Example: 1
11
Another Example:
12
Example
Another Example:
14
Hierarchical Inheritance
If multiple derived classes are created from the same base, this kind of Inheritance is known
as hierarchical inheritance. In this instance, we have two base classes as a parent (base) class
as well as two children (derived) classes.
Example
15
Example:
Multilevel inheritance
Multilevel inheritance, the features that are part of the original class, as well as the class that
is derived from it, are passed on to the new class. It is similar to a relationship involving
grandparents and children.
16
Example:
Another Example:
17
Polymorphism in Python
What is polymorphism?
Polymorphism refers to having multiple forms. Polymorphism is a programming term that
refers to the use of the same function name, but with different signatures, for multiple types.
Output:
Example:
Encapsulation in Python
19
Protected Members
Protected members in C++ and Java are members of a class that can only be accessed within
the class but cannot be accessed by anyone outside it. This can be done in Python by
following the convention and prefixing the name with a single underscore.
The protected variable can be accessed from the class and in the derived classes (it can also
be modified in the derived classes), but it is customary to not access it out of the class body.
The __init__ method, which is a constructor, runs when an object of a type is instantiated.
Example:
Another Example
20
Private Members
Private members are the same as protected members. The difference is that class members
who have been declared private should not be accessed by anyone outside the class or any
base classes. Python does not have Private instance variable variables that can be accessed
outside of a class.
However, to define a private member, prefix the member's name with a double
underscore "__".
Python's private and secured members can be accessed from outside the class using Python
name mangling.
Example:
21
Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users. The users
only interact with the basic implementation of the function, but inner working is hidden. User
is familiar with that "what function does" but they don't know "how it does."
In simple words, we all use the smartphone and very much familiar with its functions such as
camera, voice-recorder, call-dialing, etc., but we don't know how these operations are
happening in the background. Let's take another example - When we use the TV remote to
increase the volume. We don't know how pressing a key increases the volume of the TV. We
only know to press the "+" button to increase the volume.
22
A class that consists of one or more abstract method is called the abstract class. Abstract
methods do not contain their implementation. Abstract class can be inherited by the subclass
and abstract method gets its definition in the subclass. Abstraction classes are meant to be the
blueprint of the other class. An abstract class can be useful when we are designing large
functions. An abstract class is also helpful to provide the standard interface for different
implementations of components. Python provides the abc module to use the abstraction in the
Python program. Let's see the following syntax.
Example -
23
Output:
Explanation -
In the above code, we have imported the abc module to create the abstract base class. We
created the Car class that inherited the ABC class and defined an abstract method named
mileage(). We have then inherited the base class from the three different subclasses and
implemented the abstract method differently. We created the objects to call the abstract
method.
Example –
24
o An Abstract class can contain the both method normal and abstract method.
o An Abstract cannot be instantiated; we cannot create objects for the abstract class.
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.
25
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.
We can pass any number of arguments at the time of creating the class object, depending
upon the __init__() definition. It is mostly used to initialize the class attributes. Every class
must have a constructor, even if it simply relies on the default constructor.
Example:
Another Example:
Example:
Another Example:
29
In the above code, the object st called the second constructor whereas both have the same
configuration. The first method is not accessible by the st object. Internally, the object of the
class will always call the last constructor if the class has multiple constructors.
Example
31