Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Unit-4

Object Oriented Programming


Introduction
• Given any problem, the approach used to solve the
problem programmatically is called as programming
paradigm.
• There are 3 types of paradigms: Procedural
Programming, Object Oriented Programming and
Iterative Programming.
• Python adopts the features of both procedural and
object oriented programming paradigms, hence it is
called a hybrid programming language.
Procedure Oriented Programming
• Procedure oriented paradigm uses a linear top-down approach and
treats data and procedures as two different entities. Based on the
concept of a procedure call, Procedural Programming divides the
program into procedures, which are also known as routines or
functions, simply containing a series of steps to be carried out.
• Advantages:
• Procedural Programming is excellent for general-purpose
programming.
• The code can be reused in different parts of the program,
without the need to copy it.
• The program flow can be tracked easily.
Object Oriented Programming
• We create classes in object-oriented programming. A class
contains both data and functions. When we want to create
something in memory, we create an object, which is an instance of
that class. So, for example, we can declare a Customer class, which
holds data and functions related to customers. If we then want
our program to create a customer in memory, we create a new
object of the Customer class.
Advantages:
• Modularity for easier troubleshooting
• Reuse of code through inheritance
• Flexibility through polymorphism
• Effective problem solving
Sub-dividing the problem
• As programs get more complex and grow in size, it becomes
extremely important to write code that is easy to understand.
• A programmer can never keep a million-line program in mind at
the same time to debug errors.
• Hence, there is a need to break large programs into multiple
smaller pieces that are easier to manage and debug.
• A better approach to this would be to use object-oriented
approach.
Built-in Objects
stuff = list()
stuff.append('python')
stuff.append('chuck')
stuff.sort()
print (stuff[0])
print (stuff.__getitem__(0))
print (list.__getitem__(stuff,0))

- Demonstrate the object creation for dictionary and tuple.


Python user defined class example
class Person:
def __init__(self, name, age):
self.name=name
self.age=age

p1=Person(“John”, 30)
print(p1.name)
print(p2.age)
Python- Objects and Classes
• Python allows us to define classes to create objects.
• A class is a collection of instance variables and its related
methods that define an object type.
• A class is a blueprint or a template that defines a set of
attributes that characterize an object.
• Class variable − A variable that is shared by all instances of a
class. Class variables are defined within a class but outside any
of the class's methods. Class variables are not used as
frequently as instance variables are.
• Instance variable − A variable that is defined inside a method
and belongs only to the current instance of a class.
• Method − A special kind of function that is defined in a class
definition.
• Object − A unique instance of a class. An object comprises
both data members (class variables and instance variables)
and methods.
• A program to create a class called Employee.
Object Lifecycle
• The lifecycle of an object starts from its creation or construction
and ends with its destruction.
• The object creation is done with the help of a special method
called constructor and destruction takes place with the help of a
destructor method.
• A constructor is a special type of method which is used to
initialize the instance members of the class.
• Syntax of constructor declaration:
def __init__(self):
# body of the constructor
• Destructors are called when an object gets destroyed. Python has a
garbage collector that handles memory management automatically.
• The __del__( ) method is known as a destructor method in Python.
It is called when all references to the object have been deleted i.e.,
when an object is garbage collected.
Syntax of destructor declaration:
def __del__(self):
# body of destructor
Applications
• Classes and objects are frequently used in real world applications like
Web Development, Game Development, Scientific and Numeric
Applications, Artificial Intelligence and Machine Learning, Software
Development, Enterprise-level/Business Applications, Education
programs and training courses, Language Development etc.
Examples
1. Develop a Python program to create a class Student with instance variables
usn, name and marks. Create two objects and display the details of the students
who has got the highest mark.
2. Develop a Python program to create a class Actor with instance variables
actorid, actorname, no_movies and earnings. Create three actors and display
the details of the actor whose average earning is the minimum.
3. Develop a Python program which creates the class Circle that has member
radius. Include methods to do the following.
a. Accept the radius from the user
b. Find the area of the circle
c. Find the perimeter of the circle
d. Display all the details
4. Develop a Python program to create a class Employee with members
empid, empname, empnohrs, empbasic, emphra(%),
empda(%),empit(%), empgross. Include methods to do the following:
a. Accept all values from the user. Note House rent allowance,
dearness allowance and income tax are given in %
b. Calculate the gross salary based on the formula
empgross= empbasic + empbasic*emphra + empbasic*empda -
empbasic*empit
c. Consider the overtime amount to be Rs.100 per hour. If empnohrs
>200, for every hour the employee is to be given additional payment.
Calculate the additional payment and update the gross. If
empnohrs<200, reduce Rs.100 per hour and update the gross.
5. A Multispeciality hospital wants to calculate the bill amount to be
paid by patients visiting the hospital. Bill amount includes consultation
fees and lab charges. Write a Python program to implement the class
with members- bill_id, patient_name and bill_amount. Include
methods of form:
a. __init__(bill_id, patient_name)
b. Calc_billamt (consultation_fees, labcharges)
c. Display the details – bill_id, patient_name and bill_amount
A discount of 10% can be given if the lab charges exceed Rs.25000. 5%
Discount can be given if lab charges exceeds Rs.10000/-
Inheritance
• One of the core concepts in object-oriented programming
(OOP) languages is inheritance.
• It is a mechanism that allows us to create a hierarchy of classes
that share a set of properties and methods. When one class
inherits from another, it automatically takes on all the
attributes and methods of the first class but is also free to
define new attributes and methods of its own.
• The original class is called the parent class or base class or
super class, and the new class is the child class or derived class
or sub class.
Advantages of Inheritance
• It represents real-world relationships well.
• It provides the reusability of a code. Repeating the same
code again in another class is avoided as well, more features
can be added without modifying existing ones.
• It is transitive in nature, which means that if class B inherits
from another class A, then all the subclasses of B would
automatically inherit from class A.
• Inheritance offers a simple, understandable model structure.
• Development and maintenance expenses are comparatively
reduced.
Python Inheritance Syntax
class BaseClass:
{Body}
class DerivedClass (BaseClass):
{Body}

- An object of derived class can access the base class methods


also. But an object of base class cannot access derived class
methods.
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')

# Derived class
class Car(Vehicle):
def car_info(self):
print('Inside Car class') Inside Vehicle class
Inside Car class
# Create object of Car
car = Car()

# access Vehicle's info using car object


car.Vehicle_info()
car.car_info()
The __init__( ) Method for a Child Class
• The first task Python has when creating an instance from a child class
is to assign values to all attributes in the parent class. To do this, the
__init__() method for a child class needs help from its parent class.
• Example: Let us model the Electric Car. It is a specific type of a car.
Hence, we can have a base class as Car and a derived-class as
Electric_Car.
The super() method in python
• In Python, the super() function is used to refer to the parent class or
superclass. It allows you to call methods defined in the parent class
from the child class.
• Syntax: super()
• Return : Return a proxy object which represents the parent’s class.
super().__init__() line tells Python to call the __init__() method from
ElectricCar’s parent class, which gives an ElectricCar instance all the
attributes of its parent class. The name super comes from a convention
of calling the parent class a superclass and the child class a subclass
Class Variables and Instance Variables
Class Methods
• Class methods are methods that are called on the class itself, not on
a specific object instance. Therefore, it belongs to a class level, and
all class instances share a class method.
● A class method is bound to the class and not the object of the
class. It can access only class variables.
● It can modify the class state by changing the value of a class
variable that would apply across all the class objects.
• In method implementation, if we use only class variables, we should
declare such methods as class methods. The class method has a cls
as the first parameter, which refers to the class. The class method
can be called using ClassName.method_name() as well as by using
an object of the class.
Examples
• Develop a Python program using class variables to count the number of
objects getting created for a class and display the same.
• Develop a Python program to create a class Player with member variables
name, matches_played. Derive a class Batsman from Player. Class
Batsman has a member variable runs_scored. Create a Batsman object.
Calculate and display the average runs scored by the Batsman.
• Develop a Python program to create a class Person with members – name
and age. Derive another class Patient with members pid and doctorname.
The program should include the following functionalities.
- Accept a patient id and display his/her details.
- Accept the name of the patient and display the names of the doctor
treating him/her.
Operator overloading
• In Python, we can change the way operators work for user-
defined types.
• For example, the + operator will perform arithmetic addition
on two numbers, merge two lists, or concatenate two
strings.
• This feature in Python that allows the same operator to have
different meaning according to the context is called operator
overloading.
Python Special Functions
• Functions that begin and end with double underscore “__” are
called special functions in python. They perform special tasks.
• For example, the __init__().
• Similarly, when we want to overload any of the operators, we
need to implement the special functions in the user defined
types.
Overloading the + operator
class A:
def __init__(self, a):
self.a = a

# adding two objects


def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
Complex number addition
• Create a class called complex, define a parameterized constructor to initialize
real and imaginary parts.
• Overload the + operator to add 2 given complex numbers and assign it to the
third complex number.
Overloading the greater than operator >
class Complex:
def __init__(self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;

def __add__(self, C2):


temp=Complex(0, 0)
temp.real = self.real + C2.real;
temp.imaginary = self.imaginary + C2.imaginary;
return temp;

C1 = Complex(3, 2);
print("Complex number 1 :", C1.real, "+ i" + str(C1.imaginary))

C2 = Complex(9, 5);
print("Complex number 2 :", C2.real, "+ i" + str(C2.imaginary))

C3 = C1 + C2;
print("Sum of complex number :", C3.real, "+ i"+ str(C3.imaginary))
Example
• Develop a Python program to create a class Time with data
members – hours and minutes. Include the following methods:
• A parameterized constructor to set values to the hours and
minutes,
• A method ‘accept’ to accept the values for the members from the
user.
• Overload the + operator to add two given times. Ex. If Time1 has
hours=11 minutes=50 and Time2 has hours =4 minutes =40, then
Time3 should be hours=16 minutes=30
• A method to display the all the time objects.
• Create two objects of class Time and assign the sum of these two
objects to a third object.
Exceptions
• Errors detected during execution of programs are called
exceptions. Even if a statement or expression is syntactically
correct, it may cause an error when an attempt is made to
execute it. An exception is an event raised that disrupts the
normal flow of the program's instructions and is seen
everywhere in Python.
• Situations where exceptions can occur:
• Division by 0
• Opening a file
• Index out of bound ---- etc.
• Example --
Built-in Exception types in Python
• Python has a number of built-in exceptions that are derived from the
Exception class.
• Some of them are listed below:
1. SyntaxError: This exception is raised when a syntax error is
encountered in the code, such as a missing colon, wrong keyword etc.
2. TypeError: This exception is raised when an operation or function is
applied to a wrong type, such as dividing 2 strings.
3. ZeroDivisionError: This exception is raised when we try to divide a
number by 0.
4. KeyError: This exception is raised when a key is not found in the
dictionary.
5. NameError: When a function is not found in the current scope.
6. AttributeError: When an attribute or method is not found on an
object.
7. ImportError: This exception occurs when an import statement
fails to find or load the module.
8. IndexError: When the index is out of range for the collection
types.
Exception Handling
• Exception handling allows us to separate error-handling code
from normal code.
• The main advantage of exception handling is that it allows the
smooth ending of the programs when exceptions occur, instead
of abrupt ending.
• Exceptions must be class objects
• For class exception, we can use a try statement with an except
clause which mentions a particular class.
Python Exception Handling Mechanism
1. Exception handling is managed by the following 4 keywords:
1. try 2. except 3. finally 4. raise
• Format for handling exception:
try:
# Some Code....
except:
# executes when an exception occurs
# Handling of exception (if required)
else:
# executes if no exception
finally:
# Some code .....(always executed)
Examples
• 1. Input a number from the keyboard and raise an exception
if the input is not a number.
• 2. Write a python program that accepts two numbers from
the user and performs their division. It should raise an
exception for division by zero error, value error and have a
finally block.
• Write a program to demonstrate the use of try, except and
else in python exception handling.
User Defined Exceptions
• When programs for real life applications in Python are written,
there are many constraints on the values which the variables can
take in the program. For example, age cannot have a negative
value. When a person inputs a negative value for age, the program
should show an error message.
• These type of errors cannot be caught by built-in exception types.
Hence, we need to define our own exception classes that derive
from the Exception class.
• The keyword raise is used to raise a specific exception.
Example: Exception that handles negative
numbers in squareroot operation
Examples
• Write a python program to check the validity of the age. Raise an
exception if the entered age is less than 0.
• Write a Python program that demonstrates handling of exceptions
in inheritance tree. Create a base class called “Father” and a
derived class called “Son” which extends the base class. In Father
class, implement a constructor which takes the age and throws the
exception WrongAge( ) when the input age<0. In Son class,
implement a constructor that checks both father and son’s age and
throws an exception if son’s age is greater than or equal to father’s
age.

You might also like