0% found this document useful (0 votes)
14 views

Unit-3 - OOP in Python - Updated

This document discusses object-oriented programming (OOP) concepts in Python, including classes, objects, and methods. It provides examples of defining a class called Car with properties like name and color, and methods like description() and max_speed(). The key OOP concepts of encapsulation, inheritance, and polymorphism are also introduced. An example program demonstrates creating BankAccount objects with deposit, withdraw, and display methods.

Uploaded by

Lol Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit-3 - OOP in Python - Updated

This document discusses object-oriented programming (OOP) concepts in Python, including classes, objects, and methods. It provides examples of defining a class called Car with properties like name and color, and methods like description() and max_speed(). The key OOP concepts of encapsulation, inheritance, and polymorphism are also introduced. An example program demonstrates creating BankAccount objects with deposit, withdraw, and display methods.

Uploaded by

Lol Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

PROGRAMMING WITH PYTHON

Unit-3
Object-Oriented Programming and
Multi-threading:
What Is Object-Oriented
Programming (OOPs) in python?
In Python, OOPs stands for Object-Oriented Programming. It is a
programming paradigm that focuses on the use of objects and
classes to create programs.

An object is a group of interrelated variables and functions.

These variables are often referred to as properties of the object,


and functions are referred to as the behavior of the objects.

It aims to implement real-world entities like inheritance,


polymorphisms, encapsulation, etc. in the programming.
OOPs Concepts in Python

OOPs Concepts in Python:

1) Class
2) Objects
3) Polymorphism
4) Encapsulation
5) Inheritance
6) Data Abstraction
What Is Object-Oriented
Programming (OOPs) in python?
Example of OOPs :
For example, a car can be an object. If we consider the car as an
object, its properties would be its color, model, price, brand,
etc. And its behavior/function would be acceleration, slowing
down, and gear change.
Another example – If we consider a dog as an object then its
properties would be its color, breed, name, weight, etc., and its
behavior/function would be walking, barking, playing, etc.
Object-Oriented Programming is famous because it implements
real-world entities like objects, hiding, inheritance, etc, in
programming. It makes visualization easier because it is close to
real-world scenarios.
What Is a Class?
•A straightforward answer to this question is- A class is a
collection of objects. Unlike primitive data structures, classes
are data structures that the user defines. They make the code
more manageable.

•Let’s see how to define a class below-


class class_name:
class body
•We define a new class with the keyword “class” following the
class_name and colon. And we consider everything you write
under this after using indentation as its body. To make this more
understandable, let’s see an example.
What Is a Class & Object?
•Consider the case of a car showroom. You want to store the details of
each car. Let’s start by defining a class first-
class Car:
pass
That’s it!

Objects:
•When we define a class, only the description or a blueprint of the
object is created. There is no memory allocation until we create
its object. The objector instance contains real data or information.
•Instantiation is nothing but creating a new object/instance of a class.
Let’s create the object of the above class we defined-
obj1 = Car()
Class Constructor
•The job of the class constructor is to assign the values to the
data members of the class when an object of the class is
created.
•There can be various properties of a car, such as its name, color,
model, brand name, engine power, weight, price, etc. We’ll
choose only a few for understanding purposes.
class Car:
def __init__(self, name, color):
self.name = name
self.color = color
Class Constructor
• So, the properties of the car or any other object must be inside
a method that we call __init__( ).
• This __init__() method is also known as the constructor
method. We call a constructor method whenever an object of
the class is constructed.
• Now let’s talk about the parameter of the __init__() method. So,
the first parameter of this method has to be self. Then only will
the rest of the parameters come.
• The two statements inside the constructor method are –
self.name = name
self.color = color:
Class Constructor
•This will create new attributes, namely name and color, and
then assign the value of the respective parameters to them.

•The “self” keyword represents the instance of the class.

•By using the “self” keyword, we can access the attributes and
methods of the class.

•It is useful in method definitions and in variable initialization.

•The “self” is explicitly used every time we define a method.


Class Methods
•Methods are the functions we use to describe the behavior of
objects. They are also defined inside a class.
•The methods defined inside a class other than the constructor
method are known as the instance methods. Furthermore, we
have two instance methods here – description()
and max_speed(). Let’s talk about them individually:

•description()- This method returns a string with the description


of the car, such as the name and its mileage. This method has no
additional parameter. This method uses instance attributes.
•max_speed()- This method has one additional parameter and
returns a string displaying the car’s name and speed.
Class Methods
obj2 = Car("Honda City",24.1)
print(obj2.description())
print(obj2.max_speed(150))
Program
Create a class account with necessary methods – showBalance,
withdraw, deposit and transfer. Also, implement necessary
getters and setters. Instantiate 2 objects of that class and show
different method calls using them.
class Bank_Account:
def __init__(self):
self.balance=0
print("Hello!!! Welcome to the Deposit & Withdrawal Machine")

def deposit(self):
amount=float(input("Enter amount to be Deposited: "))
self.balance += amount
print("\n Amount Deposited:",amount)

def withdraw(self):
amount = float(input("Enter amount to be Withdrawn: "))
if self.balance>=amount:
self.balance-=amount
print("\n You Withdrew:", amount)
else:
print("\n Insufficient balance ")

def display(self):
print("\n Net Available Balance=",self.balance)

s = Bank_Account()

s.deposit()
s.withdraw()
s.display()
Special methods
 __init__() – constructor
 __del__() – destructor, del ob
 __str__() – string representation of object,
print ob
 __len__() – length of object, len(ob)
Principles of OOP (A.E.I.P)
• There are mainly four OOP Principles
Abstraction

Encapsulation

Inheritance

Polymorphism
Abstraction
• Abstraction refers to the act of representing
essential features without including the
background details or explanations.
• Abstraction provides you a generalized view of
your classes or object by providing relevant
information.
• Abstraction is the process of hiding the working
style of an object, and showing the information
of an object in understandable manner.
Abstraction Example
Abstract information (Necessary and
Common Information) for the object
“Mobile Phone” is make a call to any
number and can send SMS.”

Nokia 1400 Nokia 2700 Nokia 1400


Features: Features: Features:

FM Radio FM Radio
MP3 MP3
Camera Camera
Video Recording
Reading E-mails
Abstraction Example
• Example:
If somebody in your collage tell you to fill application form, you
will fill your details like name, address, data of birth,
which semester, percentage you have got etc.
• If some doctor gives you an application to fill the details, you will
fill the details like name, address, date of birth, blood
group, height and weight.
• See in the above example what is the common thing?
Age, name, address so you can create the class which
consist of common thing that is called abstract class.
That class is not complete and it can inherit by other class.
Encapsulation
• The wrapping up of data and functions into a
single unit is known as encapsulation
• The insulation of the data from direct access
by the program is called data hiding or
information hiding.
• It is the process of enclosing one or more
details from outside world through access
right.
Encapsulation

• Abstraction is a process where you show


only “relevant” data and “hide”
unnecessary details of an object from the
• Encapsulation is the process of combining
user.
data and functions into a single unit called
• Consider your mobile phone, you just
class. In Encapsulation, the data is not
need to know what buttons are to be
accessed directly; it is accessed through
pressed to send a message or make a call,
the functions present inside the class.
What happens when you press a button,
• Users are unaware about working of
how your messages are sent, how your
circuitry and hardware devices.
calls are connected is all abstracted away
from the user.
Abstraction Vs Encapsulation
• Abstraction says what details to be made visible
& Encapsulation provides the level of access right
to that visible details.
Example:
• When we switch on the Bluetooth I am able to
connect another mobile but not able to access
the other mobile features like dialling a number,
accessing inbox etc. This is because, Bluetooth
feature is given some level of abstraction.
Abstraction Vs Encapsulation
• When mobile A is connected with mobile B via Bluetooth
whereas mobile B is already connected to mobile C then A is
not allowed to connect C via B. This is because of accessibility
restriction.

A B

C
Continue..
• Encapsulation is one of the key features of object-
oriented programming. Encapsulation refers to
the bundling of attributes and methods inside a
single class.
• It prevents outer classes from accessing and
changing attributes and methods of a class. This
also helps to achieve data hiding.
• In Python, we denote private attributes using
underscore as the prefix i.e single _ or double __.
For example,
What is Encapsulation in Python?
• Encapsulation in Python describes the concept
of bundling data and methods within a single
unit.
• So, for example, when you create a class, it
means you are implementing encapsulation.
• A class is an example of encapsulation as it
binds all the data members (instance
variables) and methods into a single unit.
Continue ..
Example:
In this example, we create an Employee class by defining employee attributes
such as name and salary as an instance variable and implementing behavior
using work() and show() instance methods.
In the above program,
we defined a
Computer class.
We used __init__()
method to store the
maximum selling price
of Computer.
Inheritance
• Inheritance is the process by which objects of one class
acquire the properties of objects of another class.
Vehicle

Land Water Air

Bus Car Ship Boat Aero plane Helicopter

• Here Vehicle class can have properties like Chassis no. ,


Engine, Colour etc.
• All these properties inherited by sub classes of vehicle
class.
Continue..
• Inheritance is a way of creating a new class for
using details of an existing class without
modifying it.
• The newly formed class is a derived class (or
child class). Similarly, the existing class is a
base class (or parent class).
Here, dog1 (the object of
derived class Dog) can
access members of the base
class Animal. It's
because Dog is inherited
from Animal.
Polymorphism
• Polymorphism means ability to take more than one
form.
• For example the operation addition.
• For two numbers the operation will generate a sum.
• If the operands are strings, then the operation would
produce a third string by concatenation.
• Polymorphism is deal with method. Inheritance is deal
with class.
• In polymorphism, a method can process objects
differently depending on the class type or data type.
Let’s see simple examples to understand it better.
Polymorphism in Built-in function len()
Polymorphism in Built-in function len()
Instance, Class and Static methods
Continue..
• Class method Used to access or modify the class state. It
can modify the class state by changing the value of
a class variable that would apply across all the class
objects.
• The instance method acts on an object’s attributes. It can
modify the object state by changing the value of instance
variables.
• Static methods have limited use because they don’t have
access to the attributes of an object (instance variables)
and class attributes (class variables). However, they can
be helpful in utility such as conversion form one type to
another.
Continue..
• Instance method: Used to access or modify the object
state. If we use instance variables inside a method, such
methods are called instance methods. It must have
a self parameter to refer to the current object.
• Class method: Used to access or modify the class state.
In method implementation, if we use only class variables,
then such type of methods we should declare as a class
method. The class method has a cls parameter which
refers to the class.
• Static method: It is a general utility method that
performs a task in isolation. Inside this method, we don’t
use instance or class variable because this static method
doesn’t take any parameters like self and cls.
Class Method
Create class method using the @classmethod decorator
and classmethod() function
Create Class Method Using @classmethod Decorator
Method Definition Continue..
• All three methods are defined inside a class, and
it is pretty similar to defining a regular function.
• Any method we create in a class will
automatically be created as an instance method.
We must explicitly tell Python that it is a class
method or static method.
• Use the @classmethod decorator or
the classmethod() function to define the class
method
• Use the @staticmethod decorator or
the staticmethod() function to define a static
method.
Method Call Continue..
• Class methods and static methods can be
called using ClassName or by using a class
object.
• The Instance method can be called only using
the object of the class.
Constructors in Python
• Constructor is a special method used to create
and initialize an object of a class. On the other
hand, a destructor is used to destroy the
object.
• The constructor is executed automatically at
the time of object creation.
• For example, when we execute obj = Sample(),
Python gets to know that obj is an object of
class Sample and calls the constructor of that
class to create an object.
Continue..

• In Python, Object creation is divided into two parts in Object


Creation and Object initialization
• Internally, the __new__ is the method that creates the object
• And, using the __init__() method we can implement
constructor to initialize the object.

Syntax of a constructor:
Continue ..
Where,

• def: The keyword is used to define function.

• __init__() Method: It is a reserved method. This method gets


called as soon as an object of a class is instantiated.

• self: The first argument self refers to the current object. It


binds the instance to the __init__() method. It’s usually
named self to follow the naming convention.
Example: Create a Constructor in Python
Types of Constructors

In Python, we have the following three types of


constructors.

• Default Constructor
• Non-parametrized constructor
• Parameterized constructor
Continue ..
Default Constructor
Non-Parametrized Constructor
Parametrized Constructor
What is Destructor in Python?
• A destructor is called when an object is
deleted or destroyed.
• Destructor is used to perform the clean-up
activity before destroying the object, such as
closing database connections or filehandle.
Access Modifiers in Python
• Encapsulation can be achieved by declaring the data
members and methods of a class either as private or
protected. But In Python, we don’t have direct access
modifiers like public, private, and protected. We can
achieve this by using single
underscore and double underscores.
• Access modifiers limit access to the variables and
methods of a class. Python provides three types of
access modifiers private, public, and protected.
• Public Member: Accessible anywhere from outside of
class.
• Private Member: Accessible within the class
• Protected Member: Accessible within the class and its
sub-classes
Continue ..
Public member
Private Member
• We can protect variables in the class by
marking them private. To define a private
variable add two underscores as a prefix at the
start of a variable name.
• Private members are accessible only within
the class, and we can’t access them directly
from the class objects.
Private Member
Private Member (Public method to access private members)
Protected Member
• Protected members are accessible within the
class and also available to its sub-classes. To
define a protected member, prefix the
member name with a single underscore _.
• Protected data members are used when you
implement inheritance and want to allow data
members access to only child classes.
Protected Member
Method Overloading
• The process of calling the same method with
different parameters is known as method
overloading.
• Method overloading is the concept of
polymorphism
• It works in the same method names and
different arguments.
• Arguments different will ne based on a
number of arguments and types of
arguments.
Method Overriding
• Method overriding is the method having the
same name with the same arguments.
• It is implemented with the inheritance also..
• It mostly used for memory reducing processes.
• Using method overriding polymorphism allows
us to defines methods in the child class that have
the same name as the methods in the parent
class.
• This process of re-implementing the inherited
method in the child class is known as Method
Overriding.
Example

Output
Operator Overloading in Python
• Operator overloading means changing the
default behavior of an operator depending on
the operands (values) that we use.
• In other words, we can use the same operator
for multiple purposes.
• For example, the + operator will perform an
arithmetic addition operation when used with
numbers. Likewise, it will perform
concatenation when used with strings.

You might also like