0% found this document useful (0 votes)
5 views30 pages

Modules and Packages,Polymorphism,Abstract Class

Uploaded by

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

Modules and Packages,Polymorphism,Abstract Class

Uploaded by

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

Modules and Packages

Python Modules
•A python module can be defined as a python program
file which contains a python code including python
functions, class, or variables.
•In other words, we can say that our python code file
saved with the extension (.py) is treated as the module.
We may have a runnable code inside the python module.

•Modules in Python provides us the flexibility to organize


the code in a logical way.
Example:
•In this example, we will create a module named as
file.py which contains a function func that contains a
code to print some message on the console.

•Let's create the module named as file.py.


#displayMsg prints a message to the name being
passed.

def displayMsg(name)
• print("Hi "+name);
Loading the module in our python
code
 The import statement
 The from-import statement

•The import statement


•The import statement is used to import all the
functionality of one module into another.

•Here, we must notice that we can use the functionality of


any python source file by importing that file as the module
into another python source file.
We can import multiple modules with a single
import statement, but a module is loaded once
regardless of the number of times, it has been imported
into our file.

The syntax to use the import statement is given below

import module1,module2,........ module n


Example
import file;
name = input("Enter the name?")
file.displayMsg(name)
Output:

Enter the name?John


Hi John
The from-import statement
• Instead of importing the whole module into the
namespace, python provides the flexibility to import
only the specific attributes of a module.
• This can be done by using from? import statement.
• The syntax to use the from-import statement is given
below.
from < module-name> import <name 1>, <name
2>..,<name n>
calculation.py

#place the code in the calculation.py


def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
Main.py
from calculation import summation
#it will import only the summation() from calculation.py

a = int(input("Enter the first number"))


b = int(input("Enter the second number"))
print("Sum = ",summation(a,b))

‘’’we do not need to specify the module name while


accessing summation()’’’
Output
Enter the first number10
Enter the second number20
Sum = 30

•The from...import statement is always better to use if


we know the attributes to be imported from the
module in advance. It doesn't let our code to be heavier.
We can also import all the attributes from a module by
using *.

•Consider the following syntax.


from <module> import *
Renaming the module
•Python provides us the flexibility to import some module
with a specific name so that we can use this name to use
that module in our python source file.

•The syntax to rename a module is given below.


import <module-name> as <specific-name>
Example
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))
Output
Enter a?10
Enter b?20
Sum = 30
Python Packages
The packages in python facilitate the developer with the application
development environment by providing a hierarchical directory structure where a
package contains sub-packages, modules, and sub-modules.
The packages are used to categorize the application level code efficiently. Let's
create a package named Employees in your home directory.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name ITEmployees.py on the path
/home/Employees. ITEmployees.py
def getITNames():
List = ["John", "David", "Nick", "Martin"]
return List;
3.Similarly, create one more python file with name BPOEmployees.py and create
a function getBPONames().

Now, the directory Employees which we have created in


the first step contains two python modules. To
make this directory a package, we need to include one
more file here, that is init .py which contains the
import statements of the modules defined in this
directory.
init .py

from ITEmployees import getITNames


from BPOEmployees import getBPONames

5. Now, the directory Employees has become the


package containing two python modules. Here we must
notice that we must have to create __init__.py inside a
directory to convert this directory to a package.
6.To use the modules defined inside the package
Employees, we must have to import this in our python
source file. Let's create a simple python source file at
our home directory (/home) which uses the modules
defined in this package
Test.py

import Employees
print(Employees.getNames())
Polymorphism
• The word polymorphism means having many forms.
• In programming, polymorphism 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.
1.Function Overloading
Two or more methods have the same name but different numbers of parameters or
different types of parameters, or both. These methods are called overloaded
methods, and this is called method overloading.

Example of inbuilt functions


# len() being used for a string
print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))
Userdefined function
# A simple Python function to demonstrate
# Polymorphism

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


return x + y+z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
polymorphism in Python using inheritance
and method overriding
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!“
# Create a list of Animal objects
animals = [Dog(), Cat()]
# Call the speak method on each object
for animal in animals:
print(animal.speak())
Output

Woof!
Meow!
Operator Overloading
• It means giving extended meaning beyond their
predefined operational meaning.
• For example, operator + is used to add two integers as
well as join two strings and merge two lists.
• It is achievable because ‘+’ operator is overloaded by
int class and str class.
# Python program to show use of + operator for different purposes.

print(1 + 2)

# concatenate two strings


print("Geeks"+"For")

# Product two numbers


print(3 * 4)

# Repeat the String


print("Geeks"*4)
# Python Program illustrate how to overload an binary + 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)
# Python Program to perform addition of two complex numbers using binary
+ operator overloading.

class complex:
def __init__(self, a, b):
self.a = a
self.b = b

# adding two objects


def __add__(self, other):
return self.a + other.a, self.b + other.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)
# Python program to overload a comparison operators

class A:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
Binary Operators
Operator Magic Method
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
>> __rshift__(self, other)
<< __lshift__(self, other)
& __and__(self, other)
| __or__(self, other)
^ __xor__(self, other)
Comparison Operator

Operator Magic Method


< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
__ge__(self,
>=
other)
__eq__(self,
==
other)
__ne__(self,
!=
other)
• Abstract Class
• An abstract class can be considered a blueprint for
other classes.
• It allows you to create a set of methods that must be
created within any child classes built from the abstract
class.
• A class that 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.
• By defining an abstract base class, you can define a
common Application Program Interface(API) for a
set of subclasses.
Abstract Class

By default, Python does not provide abstract classes.


Python comes with a module that provides the base for
defining Abstract Base classes(ABC) and that module
name is ABC.

ABC works by decorating methods of the base class as


an abstract and then registering concrete classes as
implementations of the abstract base.

A method becomes abstract when decorated with the


keyword @abstractmethod(Decorator)
# Python program showing
# abstract base class work
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
# overriding abstract method
def noofsides(self):
class Hexagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 6 sides")
class Quadrilateral(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 4 sides")
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()

You might also like