0% found this document useful (0 votes)
2 views31 pages

Python OOPs Concepts

The document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, methods, inheritance, polymorphism, encapsulation, and data abstraction. It explains how these principles allow for code reusability and the organization of programs using real-world entities. Additionally, it covers the creation and use of classes, constructors, and the differences between object-oriented and procedure-oriented programming.

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views31 pages

Python OOPs Concepts

The document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, methods, inheritance, polymorphism, encapsulation, and data abstraction. It explains how these principles allow for code reusability and the organization of programs using real-world entities. Additionally, it covers the creation and use of classes, constructors, and the differences between object-oriented and procedure-oriented programming.

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

1

Python OOPs Concepts


Like other general-purpose programming languages, Python is also an object-oriented
language since its beginning. It allows us to develop applications using an Object-Oriented
approach. In Python, we can easily create and use classes and objects.

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.

Major principles of object-oriented programming system are given below.

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.

It provides the re-usability of the code.

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.

Object-oriented vs. Procedure-oriented Programming


languages
The difference between object-oriented and procedure-oriented programming is given below:
4

Python Class and Objects


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.

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

Creating classes in Python


In Python, a class can be created by using the keyword class, followed by the class name. The
syntax to create a class is given below.

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.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

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.

Delete the Object


We can delete the properties of the object or object itself by using the del keyword. Consider
the following example.

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

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-
level inheritance is archived when a derived class inherits another derived class. There is no
limit on the number of levels up to which, the multi-level inheritance is archived in python.
10

The syntax of multi-level inheritance is given below.

Example: 1
11

Another Example:
12

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.
13

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.

Example of in-built polymorphic functions:

Output:

Examples of user-defined polymorphic functions:


18

Polymorphism with Class Methods


For loops that iterate through multiple objects are created. Next, call the methods without
caring about what class each object belongs to. These methods are assumed to exist in every
class.

Example:

Encapsulation in Python
19

Encapsulation is one of the most fundamental concepts in object-oriented programming


(OOP). This is the concept of wrapping data and methods that work with data in one unit.
This prevents data modification accidentally by limiting access to variables and methods. An
object's method can change a variable's value to prevent accidental changes. These variables
are called private variables.

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

Why Abstraction is Important?


In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the
complexity. It also enhances the application efficiency.

Abstraction classes in Python


In Python, abstraction can be achieved by using abstract classes and interfaces.

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.

Abstract Base Classes


An abstract base class is the common application program of the interface for a set of
subclasses. It can be used by the third-party, which will provide the implementations such as
with plugins. It is also beneficial when we work with the large code-base hard to remember
all the classes.

Working of the Abstract Classes


Unlike the other high-level language, Python doesn't provide the abstract class itself. We
need to import the abc module, which provides the base for defining Abstract Base classes
(ABC). The ABC works by decorating methods of the base class as abstract. It registers
concrete classes as the implementation of the abstract base. We use
the @abstractmethod decorator to define an abstract method or if we don't provide the
definition to the method, it automatically becomes the abstract method. Let's understand the
following example.

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

Constructors can be of two types.

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.

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This method is
called when the class is instantiated. It accepts the self-keyword as a first argument which
allows accessing the attributes or method of the class.

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.

Consider the following example to initialize the Employee class attributes.


26

Counting the number of objects of a class


The constructor is called automatically when we create the object of the class. Consider the
following example.

Python Non-Parameterized Constructor


The non-parameterized constructor uses when we do not want to manipulate the value or the
constructor that has only self as an argument. Consider the following example.
27

Example:

Another Example:

Python Parameterized Constructor


The parameterized constructor has multiple parameters along with the self. Consider the
following example.
28

Example:

Another Example:
29

Python Default Constructor


When we do not include the constructor in the class or forget to declare it, then that becomes
the default constructor. It does not perform any task but initializes the objects. Consider the
following example.

More than One Constructor in Single class


30

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.

Python built-in class functions

Example
31

Built-in class attributes


Along with the other attributes, a Python class also contains some built-in class attributes
which provide information about the class.

The built-in class attributes are given in the below table.

You might also like