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

1523_67_122_Module_4

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, encapsulation, and polymorphism. It explains how to create classes and objects, the role of constructors and destructors, and the importance of exception handling in Python. Additionally, it covers advanced topics such as method resolution order, operator overloading, and abstract classes.

Uploaded by

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

1523_67_122_Module_4

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, encapsulation, and polymorphism. It explains how to create classes and objects, the role of constructors and destructors, and the importance of exception handling in Python. Additionally, it covers advanced topics such as method resolution order, operator overloading, and abstract classes.

Uploaded by

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

Module 4

OBJECT ORIENTED PROGRAMMING(OOP)


- Procedural programming gives importance to functions whereas object oriented programming
gives importance to objects.
- Classes and objects are the two main aspects of object-oriented programming.
- Class fruit: objects are orange,apple,banana
- Class car: objects are toyota, audi etc
- Class students: objects are dhanya, praveen etc
- Each class is a collection of data and methods(functions) that act on those data.
- Each object is an instance of a class.
- Student class has some attributes like name,rollno,class etc and some functions to read and
print the student data.
-
The basic concepts related to OOPs are:

- Classes
- Objects
- Encapsulation
- Data hiding
- Inheritance
- polymorphism

Creating a class:

- To create a class, use the keyword ‘class’

Eg: class student:

statements
Creating an object:

s1 = student()

__init__() function:

- All classes have a function called __init__(), which is always executed when the class is
being initiated.
- Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created
Constructors:

- used for instantiating an object.


- to initialize(assign values) the data members of the class when an object of class is created.
- __init__() method is called the constructor and is always called when an object is created

Syntax:

def __init__(self):

# body of the constructor


Types of constructors :
● default constructor : doesn’t accept any arguments
● parameterized constructor : accepts arguments

def __init__(self): def __init__(self, f, s):


Destructors:

- Destructors are called when an object gets destroyed.


- The __del__() method is a known as a destructor

Syntax of destructor declaration :


def __del__(self):

# body of destructor
Inheritance
- Mechanism of deriving a new class from an existing class.
- Parent class is the class being inherited from, also called base class.
- Child class is the class that inherits from another class, also called derived
class.
Types of Inheritance:
1) Single-level
2) Mutli-level
3) multiple
Single inheritance:

Student : rollno, name

Test: marks

Multi-level inheritance:

Student: rollno, name

Test: marks

Grade: calculating grade


Multiple inheritance:

Student: rollno,name

Test:marks Sports: sp

Result: finding total marks and displaying all details


Data hiding:

- Mechanism for hiding the data of a class from the outside world.
- In a class, data may be private or public.
- Private data members are not accessible by the outside world. It can be
accessed only by the member functions of the same class.
- Such data are to be prefixed with double underscore.
HYBRID INHERITANCE
Method Resolution Order

MRO is a concept used in inheritance. It is the order in which a method is searched for in a classes hierarchy
and is especially useful in Python because Python supports multiple inheritance.

In Python, the MRO is from bottom to top and left to right. This means that, first, the method is searched in the
class of the object. If it’s not found, it is searched in the immediate super class. In the case of multiple super
classes, it is searched left to right, in the order by which was declared by the developer. For example:
Polymorphism
- Means many forms.
- Eg: + operator :
- used to perform arithmetic addition operation. Or it can be used to perform
concatenation.
- Thus it can carry out different operations for distinct data types.

Function Polymorphism:

- Same function can be used to run with different data types


- Eg: len.

len(‘python’) or len([12,23,33]) or len({‘name’:’xxx’,rno:2,’class’:’s3’})


Method Overloading

def product(a, b, c):


p=a*b*c
print(p)

def product(a, b):


p=a*b
print(p)

product(4, 5)
Class polymorphism:

- Python allows different classes to have methods with the same name.
Operator Overloading
- We can change the meaning of an operator depending upon the operands used.
- For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or
concatenate two strings.
- The feature that allows the same operator to have different meaning according to the context is called
operator overloading.

Special Functions:
- Class functions that begin with double underscore __ are called special functions in Python.

__str__ method:

- represents the class objects as a string.


- It is called when a print() is invoked on a particular object. And it returns a string.
Overloading Comparison Operators:
ABSTRACT CLASS
- A class which contains one or more abstract methods is called an abstract class.
- An abstract method is a method that has a declaration but does not have an
implementation.
- Python comes with a module which provides the base for defining Abstract Base
classes(ABC) and that module name is ABC.
-
Create an Abstract Base Class called Shape that include abstract methods area() and
circumference(). Then derive two classes Circle and Rectangle from the Shape class and implement
the area() and circumference() methods . Write a Python program to implement above concept. (
university question)
EXCEPTION HANDLING
We can make certain mistakes while writing a program that lead to errors when we try to run it.
A python program terminates as soon as it encounters an unhandled error. These errors can be
broadly classified into two classes:

Syntax errors
Logical errors (Exceptions)
Exception:
- is an abnormal condition that is caused by a runtime error in the program.
- Disturbs the normal flow of the program.
- If it is not handled properly, the program will be terminated abruptly without
completing the remaining portions of the program.
- Some built-in exceptions are:
- ArithmeticError: deals with numeric calculations.
- TypeError: raised when an invalid operation is made for a specified datatype.
- ImportError: raised when an import statement fails.
- IndentationError: raised when indentation is not specified properly.
- IndexError: raised when an index is not found in a sequence.
- ZeroDivisionError: raised when division or modulo by zero is done.
- KeyError: Raised when a key is not found in a dictionary.
- NameError: Raised when a variable is not found in local or global scope.
Handling Exceptions:

- Using the keywords ‘try’ and ‘except’


- In the try block, we write the code that is likely to cause an error.
- An except block is used which catches the exception thrown by the try block and
handles it.

Syntax:
try:

a=10

b=0

print(a/b)

except ArithmeticError:

print('error: division by zero')

print('sum is ',a+b)

print('difference is ',a-b)
The except Clause with No Exceptions
Except clause with multiple exceptions:

Syntax:
try...finally:

- The finally block is a place to put any code that must execute, whether the
try-block raised an exception or not.
- We cannot use else and finally clauses together with a try block.
- It is generally used to release external resources(like closing a file,
disconnecting a network)

Syntax:

try:
Statements
finally:
finally_Statements #executed always after the try block
Raising an exception:

- We can also raise exceptions whenever needed.


User-defined Exceptions:

- We can also define our own exceptions.


Q) Write a program that validates the name and age of a user to determine
whether the person can cast vote or not using exceptions.
Questions
1) Write a Python program to implement the addition, subtraction, and
multiplication of complex numbers using classes. Use constructors to create
objects. The input to the program consist of real and imaginary parts of the
complex numbers.
2) Write a Python program to create a class representing a shopping cart.
Include methods for adding and removing items, and calculating the total
price.
3) Write a Python program to implement a student class with attributes name,
rollno and marks of 5 subjects. Create 5 student objects and find their
percentage and display the students details. Use appropriate member
functions.

You might also like