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

Unit 5 CTPS

The document outlines Module V of a B.Tech course on Computational Thinking and Problem Solving with Python, focusing on Object-Oriented Programming (OOP), file handling, modules, and packages. It covers key OOP concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, along with practical examples. The module emphasizes the importance of inheritance in code reusability and organization within Python programming.

Uploaded by

netunimate
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)
2 views165 pages

Unit 5 CTPS

The document outlines Module V of a B.Tech course on Computational Thinking and Problem Solving with Python, focusing on Object-Oriented Programming (OOP), file handling, modules, and packages. It covers key OOP concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, along with practical examples. The module emphasizes the importance of inheritance in code reusability and organization within Python programming.

Uploaded by

netunimate
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/ 165

Computational Thinking and Problem Solving

with Python Programming (CTPS)


B.Tech. 2024-2028 Semester I CSE All Sections

Module - V
Unit – V (OOPs, FILES, MODULES, PACKAGES)

OUTLINE
OOPs concepts FILES AND MODULES
▪ Class ▪ Introduction
▪ Object ▪ Files and file handling
▪ Inheritance-Types of inheritance, ▪ Exceptions and Exception handling
▪ Polymorphism- Types of Polymorphism ▪ Modules
▪ Encapsulation ▪ Packages, Importing Module from a
▪ Abstraction, Methods and Constructure Package
Module V
OOPs, FILES, MODULES, PACKAGES

Python Objects and Classes

I ntroduc tion Python Using Capstone Projec t 12/4/2024 3


Module V Python Objects and Classes
OOPs, FILES,
MODULES, PACKAGES

▪ Python follows object-oriented programming paradigm.

▪ It deals with declaring Python classes, creating objects from them


and interacting with the users.

▪ In an object-oriented language, the program is split into self-


contained objects or you can say into several mini-programs.

▪ Each object is representing a different part of the application which


can communicate among themselves.

I ntro d uctio n P ytho n Using Cap sto ne P r o j ect 1 2 /4 /2 0 2 4 4


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

Class
I ntroduc tion Python Using Capstone Projec t
Object 12/4/2024 5
Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

• A class in python is the blueprint from which specific


objects are created. It lets you structure your software in a
particular way.

• Classes allow us to logically group our data and function in


a way that it is easy to reuse and a way to build upon if need to
be.

I ntro d uctio n P ytho n Using Cap sto ne P r o j ect 1 2 /4 /2 0 2 4 6


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES
# Example for create a class named MyClass, with a property named x:

# Example for create an object named p1, and print the value of x:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 7


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES
# Example for create a class named MyClass, with a property named x:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 8


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 9


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 10


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 11


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 12


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 13


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 14


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 15


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 16


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 17


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 18


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 19


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 20


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 21


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 22


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 23


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 24


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 25


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 26


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 27


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 28


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 29


Module V Python Objects and Classes
OOPs, FILES,
MODULES, PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 30


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 31


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 32


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 33


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 34


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 35


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 36


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 37


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 38


Module V
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 39


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 40


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 41


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 42


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 43


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 44


Module V
OOPs, FILES, MODULES, PACKAGES Python Objects and Classes

I ntroduc tion Python Using Capstone Projec t 12/4/2024 45


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 46


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 47


Module V Python Objects and Classes
OOPs, FILES,
MODULES, PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 48


Module V
OOPs, FILES, MODULES, PACKAGES
Python Objects and Classes
Summary

I ntroduc tion Python Using Capstone Projec t 12/4/2024 49


Module V
OOPs, FILES, MODULES, PACKAGES Python Objects and Classes
Complete Program
The actual object is shown below. We include the method drawCircle to display the image of a circle.
We set the default radius to 3 and the default colour to blue:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 50


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 51


Module V Python Objects and Classes
OOPs, FILES, MODULES,
PACKAGES

I ntroduc tion Python Using Capstone Projec t 12/4/2024 52


Module V
OOPs, FILES, MODULES, PACKAGES Inheritance

▪ Inheritance allows us to inherit attributes and methods from the


base/parent class.

▪ This is useful as we can create sub-classes and get all of the


functionality from our parent class.

▪ Then we can overwrite and add new functionalities without


affecting the parent class.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 53
Module V
OOPs, FILES, MODULES, PACKAGES
Inheritance

▪ Let’s understand the concept of parent class and child class with an
example.
▪ As we can see in the image, a child inherits the properties from the father.
Similarly, in python, there are two classes:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 54


Module V
OOPs, FILES, MODULES, PACKAGES Inheritance

1. Parent class ( Super or Base class)


2. Child class (Subclass or Derived class )

▪ A class which inherits the properties is known as ‘Child Class’


whereas a class whose properties are inherited is known as
‘Parent Class’.

▪ Inheritance refers to the ability to create Sub-classes that


contain specializations of their parents.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 55


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

▪ Inheritance is a fundamental concept in Python’s object-oriented


programming.

▪ It allows a class, known as the child class, to inherit the attributes


and methods of another class, referred to as the parent class.

▪ This mechanism promotes code reusability and logical


organization of code.

▪ It is further divided into four types namely single, multilevel,


hierarchical and multiple inheritances. Refer the below image to get
a better understanding.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 56
Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

12/4/2024 57
Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

I ntroduc tion Python Using Capstone Projec t 12/4/2024 58


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Syntax for Creating Parent and Child Classes

▪ In Python, you create a parent (or base) class just like any
other class.

▪ However, when creating a child (or derived) class, you need


to pass the parent class as a parameter during the
declaration of the child class. Here’s how you can do it:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 59


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

I ntroduc tion Python Using Capstone Projec t 12/4/2024 60


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

▪ In this example, we created a Parent class with a greet method.


▪ We then created a Child class that inherits from the Parent class.
▪ As a result, the Child class has access to the greet method of the
Parent class.
▪ This is the simplest form of inheritance in Python.
▪ However, Python’s inheritance model allows for more complex
scenarios.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 61


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Single Inheritance:

▪ Single inheritance is the simplest type of inheritance where a class inherits

from a single superclass.

▪ We’ve already seen an example of this in the previous section.

▪ Here’s another example:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 62


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

I ntroduc tion Python Using Capstone Projec t 12/4/2024 63


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Single Inheritance:

▪ In this code, the Child class inherits from the Parent class and overrides the
greet method.

▪ However, it still calls the greet method of the Parent class using the super()
function.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 64


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Single Inheritance:

Example 3

I ntroduc tion Python Using Capstone Projec t 12/4/2024 65


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Multiple Inheritance:

▪ An inheritance becomes multiple inheritances when a class inherits more than


one parent class.

▪ The child class, after inheriting properties from various parent classes, has
access to all of its objects.

Example:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 66


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance Multiple Inheritance: Example:

• Here we have one Child class that


inherits the properties of three-
parent classes Parent_1, Parent_2,
and Parent_3.

• All the classes have different


functions, and all of the functions
are called using the object of the
Child class.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 67


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance


Multiple Inheritance: But suppose a child class inherits two classes having the
same function. Example 2:
• Here, the classes Parent_1 and
Parent_2 have the same class
methods, f1().

• Now, when we create a new object


of the child class and call f1() from it
since the child class is inheriting
both parent classes, what do you
think should happen?

I ntroduc tion Python Using Capstone Projec t 12/4/2024 68


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Multiple Inheritance: Example 2: So in the above example, why was the


function f1() of the class Parent_2 not inherited?

In multiple inheritances, the child class first searches for the method in
its own class. If not found, then it searches in the parent classes
depth_first and left-right order.

Since this was an easy example with just two parent classes, we can
clearly see that class Parent_1 was inherited first, so the child class will
search the method in Parent_1 class before searching in class Parent_2.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 69


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Multiple Inheritance: But for complicated inheritance problems, it gets


tough to identify the order. So the actual way of doing this is called
Method Resolution Order (MRO) in Python. We can find the MRO of
any class using the attribute __mro__.

This tells that the Child class first visited the class Parent_1 and
then Parent_2, so the f1() method of Parent_1 will be called.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 70
Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance


Multiple Inheritance: Example 3: Let’s take a bit complicated example in Python:
• Here, the class Child_1 inherits two classes – Parent_1 and
Parent_2.
• The class Child_2 is also inheriting two classes – Parent_2
and Parent_3.
• Another class, Child_3, is inheriting three classes – Child_1,
Child_2, and Parent_3.

• Now, just by looking at this inheritance, it is quite hard to


determine the Method Resolution Order for class Child_3.
So here is the actual use of __mro__.

We can see that, first, the interpreter


searches Child_3, then Child_1, followed
by Parent_1, Child_2, Parent_2, and
I ntroduc tion Python Using Capstone Projec t 12/4/2024 71
Parent_3, respectively.
Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance


Multi-level Inheritance:
For example, a class_1 is
inherited by a class_2, and
this class_2 also gets
inherited by class_3, and
this process goes on. This
is known as multi-level
inheritance.

Let’s understand with an


example:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 72


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance


Multi-level Inheritance: Here, the class Child_1 inherits the Parent class, and
the class Child_2 inherits the class Child_1.

In this Child_1 has access to functions f1() and f2() whereas Child_2 has access
to functions f1(), f2() and f3().

If we try to access the function f3() using the object of class Class_1, then an
error will occur stating:

‘Child_1’ object has no attribute ‘f3’.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 73


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance

Hierarchical Inheritance: Example: In this, various Child classes


inherit a single Parent class. The example given in the
introduction of the inheritance is an example of Hierarchical
inheritance since classes BMW and Audi inherit class Car.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 74


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance Hierarchical Inheritance: Example:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 75


Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance


Hierarchical Inheritance: Example:
▪ We have created two python classes with the class name, “BMW” and
“Audi” that have inherited the methods and properties of the class “Car”.

▪ So here classes “BMW” and “Audi” are child classes whereas “Car” is a parent
class. We have provided no additional features and methods in the class
BMW whereas there is one additional method inside the class Audi.

▪ Notice how the instance method description() of the parent class is


accessible by the objects of child classes with the help of obj1.description()
and obj2.description().

▪ And the separate method of class Audi is also accessible using


obj2.audi_desc().
I ntroduc tion Python Using Capstone Projec t 12/4/2024 76
Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance


Hierarchical Inheritance: Example:
▪ We can check the base or parent class of any class using a built-in
class attribute “ __bases__”

As we can see here, the base class of both sub-classes is Car. Now, let’s see
what happens when using “ __base__” with the parent class “Car”:

Whenever we create a new class in Python 3.x, it is inherited from a built-in basic
class
I ntroduc tion called
Python Object.
Using Capstone Projec In
t other words, the Object class is the root of all classes.
12/4/2024 77
Module V OOPs, FILES, MODULES, PACKAGES

Python Class: Inheritance


Hierarchical Inheritance: For simplicity, let’s look at another example:
▪ Here two child classes inherit the same parent
class.

▪ The class Child_1 has access to functions f1() of


the parent class and function f2() of itself.

▪ Whereas the class Child_2 has access to


functions f1() of the parent class and function
f3() of itself.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 78


Module V OOPs, FILES, MODULES, PACKAGES
Python Class: Inheritance
Hybrid Inheritance: When there is a combination of more than one form of
inheritance, it is known as hybrid inheritance. It will be more clear after this
example:
▪ In this example, two classes, ‘Child_1′ and ‘Child_2’,
are derived from the base class ‘Parent’ using
hierarchical inheritance.
▪ Another class, ‘Child_3’, is derived from classes
‘Child_1’ and ‘Child_2’ using multiple inheritances.
▪ The class ‘Child_3’ is now derived using hybrid
inheritance.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 79


Abstraction

▪ Abstraction means hiding the implementation detail , and showing


the essential details
▪ Abstract class is a Class which contains abstract methods
▪ Abstract Method is a methods which is having declaration without
definition
▪ A concrete is a class which does not contain any abstract methods
Note:
Object cannot be instantiated/ created for an abstract class. Object
can only be created for a concrete.
Abstract Class and Concrete Class

Imported Abstract class Inherited Concrete class

▪ Are imported from Abstract base class (abc)


• Inherited from the abstract class
module
• Implement /define all the abstract methods
▪ abc module contains abstract class (ABC) and
• The methods which are available in the abstract
abstract method.
class will be override in the concrete class i.e
▪ ABC -To maintain the class as an abstract
write the definition for all the methods in the
▪ Abstract methods: To decorate the abstract
abstract class.
methods
Note:
Object cannot be instantiated/ created for an abstract class. Figure 9: Relationship between abstract class and concrete
Object can only be created for a concrete class. class
Encapsulation

▪ Binding data and function into single entity

▪ It simply means wrapping of data

▪ Combining methods and variable in one place

▪ Restriction of methods and variable to a particular class

▪ Making methods or variable private


Encapsulation……

Variables
Encapsulation Methods Scope
functions
Figure 10: Demonstration of Encapsulation

Public Private

Example Example
class encap: class encap:
car=“toyota” __car=“toyota”
def brand(self): __def brand(self):
print(“toyota brand ”) print(“toyota brand ”)

Note: The scope of pubic variables/methods/functions are converted to private by entering double
underscore (__) the variable/function/methods.
Demonstration: Abstract& Concrete Class

Figure 11: Demonstration of


the relationship between
abstract and concrete class
Module V OOPs, FILES, MODULES, PACKAGES

Polymorphism in Python

▪ The word polymorphism means having many forms. In Python,


polymorphisms refer to the occurrence of something in multiple forms.

▪ A single type of entity is used to represent a variety of types in different


contexts (methods, functions, operators, objects, etc.).

▪ In programming, polymorphism also means the same function name (but


different signatures) being used for different types.

▪ The key difference is the data types and number of arguments used in
function.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 85


Module V OOPs, FILES, MODULES, PACKAGES

Polymorphism in Python
▪ As part of polymorphism, a Python child class has methods with the same
name as a parent class method. This is an essential part of programming.

▪ Polymorphism includes method overloading, method overriding, and


operator overloading.

▪ Example of inbuilt polymorphic functions:


# Python program to demonstrate in-built polymorphic functions

# len() being used for a “String”


print(len(“Python"))

# len() being used for a “List”


print(len([3, 7, 9]))
I ntroduc tion Python Using Capstone Projec t 12/4/2024 86
Module V OOPs, FILES, MODULES, PACKAGES

Polymorphism in Python
Examples of user-defined polymorphic functions:

# A simple Python function to demonstrate Polymorphism

def add(x, y, z = 0):


return x+y+z

print(add(2, 3))
print(add(2, 3, 4))

I ntroduc tion Python Using Capstone Projec t 12/4/2024 87


Module V OOPs, FILES, MODULES, PACKAGES

Polymorphism in Python
Polymorphism with class methods:

▪ The below code shows how Python can use two different class types, in the
same way.

▪ We create a for loop that iterates through a tuple of objects.

▪ Then call the methods without being concerned about which class type each
object is.

▪ We assume that these methods actually exist in each class.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 88


Module V OOPs, FILES, MODULES, PACKAGES
Polymorphism in Python
Polymorphism with class methods:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 89


Module V OOPs, FILES, MODULES, PACKAGES
Polymorphism in Python
Polymorphism with Inheritance:
▪ In Python, Polymorphism lets us define methods in the child class that have
the same name as the methods in the parent class.

▪ In inheritance, the child class inherits the methods from the parent class.

▪ However, it is possible to modify a method in a child class that it has inherited


from the parent class.

▪ This is particularly useful in cases where the method inherited from the
parent class doesn’t quite fit the child class.

▪ In such cases, we re-implement the method in the child class. This process of
re-implementing a method in the child class is known as Method Overriding.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 90
Module V OOPs, FILES, MODULES, PACKAGES
Polymorphism in Python
Polymorphism with Inheritance:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 91


Module V OOPs, FILES, MODULES, PACKAGES

Polymorphism in Python
Using Inheritance and Method Overriding:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 92


FILES AND MODULES

▪ Files and file handling

▪ Exceptions and Exception handling

▪ Modules

▪ Packages, Importing Module from a Package


Module V: OOPs, FILES, MODULES, PACKAGES BBA Sem 1_Course: Introduction to Python
Using Capstone Project

I ntroduc tion Python Using Capstone Projec t 12/4/2024 94


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project

File Handling
n
▪ In this section we will use Python’s open built in functions to
create a file object and obtain the data from the txt file.

▪ We will use Python’s Open Function to get file object.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 95


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling

Common ”modes” are


▪ ‘r’ for reading,
▪ ’w’ for writing, and
▪ ‘a’ for appending

I ntroduc tion Python Using Capstone Projec t 12/4/2024 96


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Output

I ntroduc tion Python Using Capstone Projec t 12/4/2024 97


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with the open-read () method

I ntroduc tion Python Using Capstone Projec t 12/4/2024 98


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with the open and read() method

I ntroduc tion Python Using Capstone Projec t 12/4/2024 99


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with the open and readlines () methods
Output

I ntroduc tion Python Using Capstone Projec t 12/6/2024 100


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with the open and readlines () methods

Output

I ntroduc tion Python Using Capstone Projec t 12/4/2024 101


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with the open and readlines () methods

I ntroduc tion Python Using Capstone Projec t 12/4/2024 102


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling

I ntroduc tion Python Using Capstone Projec t 12/4/2024 103


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with for loop

I ntroduc tion Python Using Capstone Projec t 12/4/2024 104


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with for loop

I ntroduc tion Python Using Capstone Projec t 12/4/2024 105


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Reading files with for loop

I ntroduc tion Python Using Capstone Projec t 12/4/2024 106


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
▪ We don’t have to read the entire file, for example, we can read the first 4
characters by entering three as a parameter to the method .read():

I ntroduc tion Python Using Capstone Projec t 12/4/2024 107


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling

▪ Once the method .read(4) is called the first 4 characters are called.

▪ If we call the method again, the next 4 characters are called.


I ntroduc tion Python Using Capstone Projec t 12/4/2024 108
BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
▪ The output for the following cell will demonstrate the process for
different inputs to the method read():

▪ We can also read one line of the file


at a time using the method readline():

I ntroduc tion Python Using Capstone Projec t 12/4/2024 109


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling

I ntroduc tion Python Using Capstone Projec t 12/4/2024 110


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling

I ntroduc tion Python Using Capstone Projec t 12/4/2024 111


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Writing Files
▪ We can open a file object using the method write() to save the text file to a list.

▪ To write the mode, argument must be set to write “w”.

▪ Let’s write a file Example2.txt with the line: “This is line A”

I ntroduc tion Python Using Capstone Projec t 12/4/2024 112


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Writing Files

Will Create new file if it does not exist and


if already exist then it will Override that existing file

I ntroduc tion Python Using Capstone Projec t 12/4/2024 113


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Writing Files

I ntroduc tion Python Using Capstone Projec t 12/4/2024 114


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Writing Files: Example 1

I ntroduc tion Python Using Capstone Projec t 12/4/2024 115


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Writing Files
We can write multiple lines:

The method .write() works similar to the method .readline(), except instead of reading a new line it
writes a new line.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 116


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Writing Files
We can write multiple lines:

You can check the file to see if your results are correct

I ntroduc tion Python Using Capstone Projec t 12/4/2024 117


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Writing Files

I ntroduc tion Python Using Capstone Projec t 12/4/2024 118


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling
Writing Files

I ntroduc tion Python Using Capstone Projec t 12/4/2024 119


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Writing Files
Will Not Create new file but just add new content to the existing file.
By setting the mode argument to append a you can append a new line as
follows:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 120


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Writing Files
By setting the mode argument to append a you can append a new line as
follows: Example 1

I ntroduc tion Python Using Capstone Projec t 12/4/2024 121


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Writing Files
By setting the mode argument to append a you can append a new line as
follows: Example 2

I ntroduc tion Python Using Capstone Projec t 12/4/2024 122


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Copying one file to another file

I ntroduc tion Python Using Capstone Projec t 12/4/2024 123


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Copying one file to another file

I ntroduc tion Python Using Capstone Projec t 12/4/2024 124


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Copying one file to another file

I ntroduc tion Python Using Capstone Projec t 12/4/2024 125


BBA Sem 1_Course: Introduction to Python
Module V: OOPs, FILES, MODULES, PACKAGES
Using Capstone Project
File Handling Copying one file to another file

I ntroduc tion Python Using Capstone Projec t 12/4/2024 126


Module V: OOPs, FILES, MODULES, PACKAGES BBA Sem 1_Course: Introduction to Python
Using Capstone Project
File Handling Copying one file to another file
▪ After reading
files, we can
also write
data into
files and
save them in
different file
formats like
.txt,
.csv, .xls
(for excel
files)
etc.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 127


Exceptions and Exception Handling

Exceptions are errors that occur during the execution of a program.

When an error occurs, Python generates an exception, which can

potentially cause the program to terminate if not handled properly.


Common Exceptions in Python

Exception Description
Raised when a division or modulo operation is
ZeroDivisionError
attempted with zero.
Raised when a function receives an argument of
ValueError
the correct type but an inappropriate value.
Raised when an operation or function is applied
TypeError
to an object of inappropriate type.
Raised when a sequence (like a list) is indexed with an
IndexError
out-of-range index.
Raised when a dictionary is accessed with a key that
KeyError
does not exist.
Common Exceptions in Python

Exception Description
Raised when trying to open a file that does not
FileNotFoundError
exist.
Raised when an invalid attribute reference or
AttributeError
assignment is attempted.
Raised when an import statement fails to find
ImportError
the module definition.
NameError Raised when a local or global name is not found.
Common Exceptions in Python

Exception Description
Raised when an I/O operation fails (e.g., when a
IOError
file cannot be opened).
Raised when the result of an arithmetic operation
OverflowError
is too large to be expressed.
IndentationError Raised when the code is not properly indented.
Raised when an error occurs that doesn't fall
RuntimeError
into any other category.
Exception Handling

• These are mechanism provided by the interpreter to handle exception that allows program
to run smoothly without termination.
• Python uses Try, Except, Else, and Finally blocks to handle exceptions.
Table 5: Basic syntax for handling exceptions

Try Except Else Finally


Instructions The block will handle Optional Optional
(functions/methods) for exception raised in the
which we are expecting try block No exception Will be executed always

*risky_operation() End_operation()
*handle_exception( ) *successful_peration()
MODULES AND PACKAGES

➢Modules

➢Packages

➢ Importing Module from a Package


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

▪ If you quit from the Python interpreter and enter it again, the
definitions you have made (functions and variables) are lost.

▪ Therefore, if you want to write a somewhat longer program, you are


better off using a text editor to prepare the input for the interpreter
and running it with that file as input instead.

▪ This is known as creating a script. As your program gets longer, you


may want to split it into several files for easier maintenance.

▪ You may also want to use a handy function that you’ve written in several
programs without copying its definition into each program.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 134
Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

▪ To support this, Python has a way to put definitions in a file and use
them in a script or in an interactive instance of the interpreter. Such
a file is called a module;

▪ definitions from a module can be imported into other modules or


into the main module (the collection of variables that you have access
to in a script executed at the top level and in calculator mode).

I ntroduc tion Python Using Capstone Projec t 12/4/2024 135


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

▪ A “module” is a file containing Python definitions and statements.


The file name is the module name with the suffix .py appended.

▪ A Python module is a file containing Python definitions and


statements.

▪ A module can define functions, classes, and variables. A module can


also include runnable code.

▪ Grouping related code into a module makes the code easier to


understand and use. It also makes the code logically organized.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 136


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

▪ Within a module, the module’s name (as a string) is available as the


value of the global variable __name__.

▪ For instance, use your favorite text editor to create a file called fibo.py
in the current directory with the following contents:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 137


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python: Create a Python Module In mathematics, the


“Fibonacci sequence” is
a sequence in which
each number is the sum
of the two preceding
ones. Numbers that are
part of the Fibonacci
sequence are known as
Fibonacci numbers,
commonly denoted Fn .
The sequence commonly
starts from 0 and 1,
although some authors
start the sequence from 1
and 1 or sometimes (as
did Fibonacci) from 1 and
2. Starting from 0 and 1,
the sequence begins

0, 1, 1, 2, 3, 5, 8, 13, 21,
I ntroduc tion Python Using Capstone Projec t 34, 55,12/4/2024
89, 144, ... 138
Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python: Import module in Python

▪ We can import the functions, and classes defined in a module to


another module using the import statement in some other Python
source file.

▪ When the interpreter encounters an import statement, it imports the


module if the module is present in the search path.

▪ A search path is a list of directories that the interpreter searches for


importing a module.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 139


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python: Import module in Python

▪ Now enter the Python interpreter and import this module with the
following command:

▪ This does not add the names of the functions defined in fibo
directly to the current namespace; it only adds the module name fibo
there.

▪ Using the module name you can access the functions:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 140


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

I ntroduc tion Python Using Capstone Projec t 12/4/2024 141


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python Example 2

Create a simple calc.py in which we define two functions, one add


and another subtract.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 142


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

Python Import from Module

▪ Python’s from statement lets you import specific attributes from


a module without importing the module as a whole.

Import Specific Attributes from a Python module

▪ Here, we are importing specific sqrt and factorial attributes from


the math module.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 143


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Python Import from Module

▪ Python’s from statement lets you


import specific attributes from a
module without importing the
module as a whole.

Import Specific Attributes from a


Python module

▪ Here, we are importing specific sqrt


and factorial attributes from the math
module.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 144
Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Import all Names

▪ The * symbol used with the import statement is used to import all the
names from a module to a current namespace.

What does import * do in Python

▪ The use of * has its advantages and disadvantages.

▪ If you know exactly what you will be needing from the module, it is
not recommended to use *, else do so.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 145


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
What does import * do in Python
# importing sqrt() and factorial from the module math

from math import *

# if we simply do "import math", then math.sqrt(16) and


# math.factorial()are required.

print(sqrt(16)) Output
print(factorial(6))
4.0
720
I ntroduc tion Python Using Capstone Projec t 12/4/2024 146
Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Locating Python Modules

▪ Whenever a module is imported in Python the interpreter looks for


several locations.

▪ First, it will check for the built-in module, if not found then it looks for a
list of directories defined in the sys.path.

Python interpreter searches for the module in the following manner –

▪ First, it searches for the module in the current directory.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 147


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Locating Python Modules

Python interpreter searches for the module in the following manner –

▪ If the module isn’t found in the current directory, Python then searches
each directory in the shell variable PYTHONPATH.

▪ The PYTHONPATH is an environment variable, consisting of a list of


directories.

▪ If that also fails python checks the installation-dependent list of


directories configured at the time Python is installed.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 148


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Locating Python Modules

Directories List for Modules

▪ Here, sys.path is a built-in variable within the sys module.

▪ It contains a list of directories that the interpreter will


search for the required module.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 149


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Locating Python Modules

Renaming the Python module

▪ We can rename the module while importing it using the keyword

I ntroduc tion Python Using Capstone Projec t 12/4/2024 150


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Renaming the Python module
# importing sqrt() and factorial from the module math

import math as mt

# if we simply do "import math", then math.sqrt(16) and


#math.factorial() are required.

print(mt.sqrt(16))
print(mt.factorial(6))]

I ntroduc tion Python Using Capstone Projec t 12/4/2024 151


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Python Built-in modules: There are several built-in modules in
Python, which you can import whenever you like.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 152


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

What is Package in Python?

▪ Package refers to a distribution of Python code that includes one


or more modules or libraries.

▪ These packages are typically published on the Python Package


Index (PyPI) and can be easily installed using pip.

▪ Python packages may contain modules, sub-packages, and


additional resources such as documentation and data files.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 153


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

What is Python PIP?

▪ Python PIP is the package manager for Python packages.

▪ We can use PIP to install packages that do not come with Python.

▪ The basic syntax of PIP commands in the command prompt is:

I ntroduc tion Python Using Capstone Projec t 12/4/2024 154


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

How to Install Python PIP?

▪ Python PIP comes pre-installed on 3.4 or older versions of


Python.

▪ To Check if PIP is Installed or not type the below command in the


terminal.

▪ This command will tell the version of the Pip if it is already


installed in the system.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 155
Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

How to Install Package with Python PIP

▪ We can install additional packages by using the Python pip install


command.

▪ Let’s suppose we want to install the Numpy using PIP.

▪ We can do it using the below command.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 156


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
How to Install Package with Python PIP

I ntroduc tion Python Using Capstone Projec t 12/4/2024 157


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

Specifying Package Version using Python PIP

▪ We can also install the package of a specific version by using the


below command..

Display Package information using Python PIP

▪ We can use the Python pip show command to display the details of
a particular package.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 158


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python

Specifying Package Version using Python PIP

▪ We can also install the package of a specific version by using the


below command.

Note:

▪ Requires column shows the dependencies required by the


NumPy package

▪ Required by shows the packages that require NumPy

I ntroduc tion Python Using Capstone Projec t 12/4/2024 159


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Get a list of locally installed Python Modules using Python PIP

▪ The Python pip list command displays a list of packages installed in


the system.

Uninstall Packages with Python PIP

▪ The Python pip uninstall command uninstalls a particular existing


package.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 160


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Uninstall Packages with Python PIP

Note: The PIP uninstall command does not uninstall the package
dependencies.

▪ If you want to remove the dependencies as well then you can see the
dependencies using the pip show command and remove each package
manually.

Search Packages with Python PIP

▪ We can search for a particular existing package using the Python pip
search command.
I ntroduc tion Python Using Capstone Projec t 12/4/2024 161
Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Using Requirement files with Python PIP

▪ Let’s suppose you want more than one package then instead of installing
each package manually, you can install all the modules in a single go.

▪ This can be done by creating a requirements.txt file.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 162


Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python
Listing additional Packages with Python PIP

▪ The Python pip freeze command is used to list packages that don’t come
pre-installed with Python.

▪ Listing Outdated Packages with Python PIP

▪ Upgrading Packages with Python PIP

▪ We can also upgrade any package to a specific version using the below
command.

▪ Downgrading Packages with Python PIP


I ntroduc tion Python Using Capstone Projec t 12/4/2024 163
Module V OOPs, FILES, MODULES, PACKAGES

Modules in Python: Random module

▪ Python Random module is an in-built module of Python that is


used to generate random numbers in Python.

▪ These are pseudo-random numbers means they are not truly


random.

▪ This module can be used to perform random actions such as


generating random numbers, printing random a value for a
list or string, etc.

I ntroduc tion Python Using Capstone Projec t 12/4/2024 164


End of Module V

You might also like