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

Unit 2 - Functions in Python[1]

This document provides an overview of functions in Python, explaining their definition, syntax, and types, including user-defined, anonymous (lambda), and recursive functions. It also covers function parameters, arguments, and the importance of modules in organizing code, along with how to create and use custom modules. Key concepts such as keyword arguments, default arguments, and the role of __init__.py in defining packages are also discussed.
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)
2 views72 pages

Unit 2 - Functions in Python[1]

This document provides an overview of functions in Python, explaining their definition, syntax, and types, including user-defined, anonymous (lambda), and recursive functions. It also covers function parameters, arguments, and the importance of modules in organizing code, along with how to create and use custom modules. Key concepts such as keyword arguments, default arguments, and the role of __init__.py in defining packages are also discussed.
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/ 72

UNIT 2: FUNCTIONS IN PYTHON

VISHNU PRIYA P M 1
FUNCTION
 Function in Python is a reusable block of code that performs a single, specific
and well defined task.
 It allows you to encapsulate a set of instructions into a single unit, which you
can then call by its name whenever you want to execute that set of
instructions.
WHY FUNCTION ?
 Code Reusability
 Modularity
 Easy Debugging
2

VISHNU PRIYA P M
HOW FUNCTION WORKS ?

VISHNU PRIYA P M 3
SYNTAX OF FUNCTION DEFINITION

VISHNU PRIYA P M 4
EXAMPLE OF FUNCTION DEFINITION

In Python, you can define a function using the def keyword
followed by the function name, a set of parentheses
containing any parameters the function takes, and a colon.
The function body is indented and contains the code that
defines what the function does.
You can also include a return statement to send a value back
as the result of the function's execution.
VISHNU PRIYA P M 5
EXAMPLE 1

# function declaration
def function():
print(“Hello world”)
# calling function
function() # function call

VISHNU PRIYA P M 6
EXAMPLE 2
def greet(name):
return "Hello, " + name + "!"

# Calling the function


message = greet(“BCA D ")
print(message) # Output: Hello, BCA D!

The greet function takes a single parameter name and returns a greeting message
VISHNU PRIYA P M 7
FUNCTION PARAMETRES

The name of the function while calling and the number


of arguments must match with the function definition.
If there is a mismatch in number of parameters passed
and declared, then an error will be returned.
If the data type of the parameter passed does not match
with that of the function, then an error is generated.
VISHNU PRIYA P M 8
FUNCTION PARAMETRES

VISHNU PRIYA P M 9
TYPES OF FUNCTIONS IN PYTHON

VISHNU PRIYA P M 10
ANONYMOUS FUNCTIONS

 Anonymous functions are known as "lambda" functions.


 Lambda functions are not declared using def keyword. Instead lambda is used.
 A lambda function is a small, inline function that doesn't have a formal name like
a regular user-defined function.
 Lambda functions are often used for short, simple operations that can be defined
in a single line of code.
 Any number of arguments can be supplied to lambda functions, but it must
contain only a single expression.

VISHNU PRIYA P M 11
ANONYMOUS FUNCTIONS

 The syntax for creating a lambda function is as follows:

lambda arguments :
expression
 Here's a basic example of a lambda function that adds two numbers:
add = lambda x, y: x + y

result = add(5, 3)

print(result) # Output: 8

VISHNU PRIYA P M 12
ANONYMOUS FUNCTIONS

1. Lambda functions have no name


2. Lambda function cannot access variables other than those in their parameter list.
3. Lambda functions can take N number of arguments
4. Lambda functions does not have any return statement
5. It could have only a single expression

VISHNU PRIYA P M 13
 Lambda functions are typically used when you need a quick function for a short task,
like passing a function as an argument to another function, working with higher-order
functions like map(), filter(), or sorted(), or creating simple key functions for sorting.

 Here's an example of using a lambda function with the sorted() function:

points = [(3, 5), (1, 9), (8, 2)]


sorted_points = sorted(points, key=lambda point: point[1]) #Sorting by the second element of each tuple

print(sorted_points) # Output: [(8, 2), (3, 5), (1, 9)]

 Lambda functions can be useful in situations where defining a full named function might
be unnecessary due to the function's simplicity.
 However, for more complex or larger functions, it's generally better to use regular user-
defined functions for clarity and maintainability.
VISHNU PRIYA P M 14
RECURSIVE FUNCTIONS

 Recursive function is a function that calls itself as part of its execution.


 Recursive functions are used to solve problems that can be broken down into smaller
instances of the same problem.
 Each recursive call works on a smaller piece of the problem until it reaches a base
case where a direct solution can be obtained without further recursion.
 Recursive functions can be a powerful tool for solving certain types of problems, but
they should be designed carefully to avoid infinite recursion and excessive
function calls.
VISHNU PRIYA P M 15
RECURSIVE FUNCTION EXAMPLE

 Suppose we want to calculate the factorial value of an integer [n! = n * (n-1)!]

def factorial(n):
if n == 0:
return 1
else
return n * factorial (n-1)

print(factorial(5)) # output will be 120

VISHNU PRIYA P M 16
calculating the factorial of a non-negative integer n:
def factorial(n): The factorial function calls itself with a smaller
if n == 0: value of n until it reaches the base case where n is 0.
return 1 This base case returns 1, and the function then starts
else: "unwinding" the recursive calls, multiplying each
return n * factorial(n - 1) value of n until the original call is complete.

result = factorial(5) # 5! = 5 * 4 * 3 * 2 * 1 = 120


print(result) # Output: 120

 When creating recursive functions, it's important to define the base case(s) that will
terminate the recursion and prevent infinite loops.
 Without a proper base case, the function would keep calling itself indefinitely and
eventually lead to a "RecursionError" due to exceeding the maximum recursion depth.

VISHNU PRIYA P M 17
USER-DEFINED FUNCTIONS IN PYTHON

 User-defined functions in Python are functions that you create yourself to perform
specific tasks according to your needs.
 They allow you to encapsulate a block of code into a reusable unit, making your code
more organized and modular.
 To define a user-defined function in Python, you use the def keyword followed by the
function name, a set of parentheses containing any parameters the function takes (if
any), and a colon (:).
 The function body is indented and contains the code that defines what the function
does.
 You can also include a return statement to send a value back as the result of the
function's execution.
VISHNU PRIYA P M 18
Here's the basic syntax for defining a user-defined function:
def function_name(parameters):

# Function body
# Code to perform the task
return result # Optional

Here's an example of a simple user-defined function:


def add_numbers(a, b):
return a + b

result = add_numbers(5, 3)
print(result) # Output: 8

VISHNU PRIYA P M 19
FUNCTIONS ARGUMENTS

 You can call a function by using this types of


formal parameters

VISHNU PRIYA P M 20
1. REQUIRED
ARGUMENTS
 Arguments must be passed on to a function in correct order.
 The number of arguments passed to a function must match with the number of
arguments specified in the function definition
def prd ( a , b):
prd = a * b
return prd
product = prd ( 12, 2)
print ( product ) # output will be 24

VISHNU PRIYA P M 21
2. KEYWORD
ARGUMENTS

 A keyword argument helps to identify arguments by specifying the name of the


parameter.
 The order of the keyword argument is not important.
 The keyword arguments passed must match with one of the arguments of the
accepting function.
 It makes the program code less complex and easy to understand

VISHNU PRIYA P M 22
when you call a function, you usually pass arguments to it. For example:

def student(name, course, fees):


print("Name:", name)
print("Course:", course)
print("Fees:", fees)

Here, name, course, and fees are the parameters of the function. When
you call the function like this:
student("Ashok", "BCA", "30000")

You're passing the arguments by their position. The first value "Ashok"
goes to name, the second "BCA" goes to course, and the third "30000"
goes to fees.
VISHNU PRIYA P M 23
What are Keyword Arguments?

Keyword arguments allow you to pass values to a function by explicitly


stating the name of the parameter. This means you don't have to follow
the exact order of the parameters.

For example, you can call the student function like this:

student(fees="30000", name="Ashok", course="BCA")

Here, you're specifying which value should go to which parameter by


using the parameter name (fees, name, course). This is called keyword
arguments.

VISHNU PRIYA P M 24
2. KEYWORD
ARGUMENTS

def student ( name, course, fees):


print(“Name: “, name)
print(“Course: “, course) # output will be
print(“Fees: “, fees)
Name: Ashok
n = “Ashok” Course: BCA
c = “BCA” Fees : 30000
f = “30000”
Student ( fees=f, name=n, course=c)

VISHNU PRIYA P M 25
3. DEFAULT
ARGUMENTS
 It allow to specify a value for a parameter
 This allow to call a function with less number of arguments defined.
 Any number of default arguments can be defined.
 Non default argument cannot be followed by the default arguments

def student ( name, course = “BCA):


# output will be
print(“Name: “, name)
print(“Course: “, course) Name: Ashok
Course: BCA
Student ( name= “Ashok”)

VISHNU PRIYA P M 26
4. VARIABLE - LENGTH
ARGUMENTS
 In cases where it is not known in prior how many arguments will be passed to a
function , python allows to make function call with arbitrary number of arguments
 An asterisk (* ) symbol is used before the parameter name.

def vlen ( course, sem, *sub_mark): # output will be


print(“Course: “, course) Course: BCA
print(“Sem: “, sem) Sem: fifth
Sub_mark: 100
for p in sub_mark: Sub_mark: 99
print(“sub_mark: “, p) Sub_mark: 90
vlen (“BCA”, “fifth”, “100”, “99”, “90”)
VISHNU PRIYA P M 27
INTRODUCTION TO MODULES

A module is a file containing Python definitions, functions,


classes, and variables that can be used in other Python programs.
Modules provide a way to organize your code and make it more
modular, reusable, and maintainable. Python has a rich collection
of built-in modules, and you can also create your own custom modules
to encapsulate related functionality.

28

VISHNU PRIYA P M
Introduction to working with modules in Python:

1.Built-in Modules: Python comes with a set of built-in modules that


provide various functionalities. Some common examples include:

a. math: Provides mathematical functions and constants.


b. random: Generates random numbers.
c. datetime: Manipulates dates and times.
d. os: Interacts with the operating system, like reading directories and
files.
e. sys: Provides access to system-specific parameters and functions.

VISHNU PRIYA P M 29
2. Importing Modules: To use functions, classes, or variables from a module, you
need to import the module into your code. The import statement is used for this
purpose. For example:

import math

print(math.sqrt(16)) # Output: 4.0

You can also use the from keyword to import specific items from a module:

from math import sqrt

print(sqrt(16)) # Output: 4.0

VISHNU PRIYA P M 30
3. Creating Custom Modules: You can create your own modules by creating a .py
file and placing your Python code inside it. For example, if you create a file named
my_module.py with the following content:
def greet(name):
return f"Hello, {name}!"

You can then use this module in another script:

import my_module

message = my_module.greet("Alice")
print(message) # Output: Hello, Alice!

VISHNU PRIYA P M 31
4. Package: A package is a collection of related modules organized in a directory
hierarchy. It includes a special __init__.py file that makes Python treat the
directory as a package. Packages allow you to organize related modules into a
coherent structure.

5. Third-party Modules: Python has a vast ecosystem of third-party modules that


you can install and use to extend your code's functionality. You can install these
modules using tools like pip (Python package manager).

pip install module_name

Common third-party modules include numpy, pandas, requests, and many others.

Using modules in Python promotes code reusability and helps manage the complexity
of larger projects. By breaking down your code into smaller, modular components, you
can work more efficiently and collaborate effectively with other developers.
VISHNU PRIYA P M 32
Example:Let's say you're writing a game with different characters. You might organize your code
like this:
my_game/

├── characters/ # This is the package
│ ├── __init__.py # This makes 'characters' a package
│ ├── hero.py # A module for the hero character
│ ├── villain.py # A module for the villain character
│ └── sidekick.py # A module for the sidekick character

VISHNU PRIYA P M 33
What is __init__.py?
In Python, the __init__.py file is an important file used to define a package. It can be empty or contain
initialization code, but its main job is to signal to Python that the directory it is in should be treated as a package.
Why is __init__.py Needed?
Without __init__.py, Python wouldn't recognize a directory as a package. In simple terms, it's like a "flag" that
tells Python, "Hey, treat this folder like a package with related modules inside!“

What Does It Do?


1.Marks a Folder as a Package: When you see a folder with an __init__.py file, that folder is considered a
package. This allows you to import modules from it.
2.Can Contain Initialization Code: You can put code in __init__.py that you want to run when the package is
imported. For example, it can help you load modules, define variables, or set up configurations when the package
is first used.
3.Allows Relative Imports: Inside a package, you can use the __init__.py file to import other modules from the
same package, making the code more modular and organized.

VISHNU PRIYA P M 34
Example:
Let’s say you have the following structure in your project:

my_project/

├── math_operations/ # This is a package (because of the __init__.py file)
│ ├── __init__.py # Special file that marks the folder as a package
│ ├── addition.py # A module with code for adding numbers
│ └── subtraction.py # A module with code for subtracting numbers
Now, you can import the modules from the math_operations package like this:

from math_operations import addition, subtraction


If the __init__.py file wasn't there, Python wouldn't know that math_operations is a package, and you wouldn't be able to
import these modules.

Can __init__.py Be Empty?


Yes, it can be completely empty! Its only job in this case is to tell Python that the folder is a package. However, you can
also add some code to it if needed.

VISHNU PRIYA P M 35
The __init__ method in Python is a special method that acts as a constructor. It’s automatically called
when you create an object from a class, and it’s used to initialize the object's attributes.

Let’s break it down simply:


What Does the __init__ Method Do?
•Initialization: When you create a new object, the __init__ method helps to set up that object with the
specific details or information you want. It’s like filling out a form when you get a new item, such as
entering your name and email when setting up a new phone or account.

Example Using a Car


Let’s look at how the __init__ method works in a Car class:

class Car: def __init__(self, model, year): # This is the constructor method self.model = model # The car's
model (e.g., Model S) self.year = year # The car's manufacturing year (e.g., 2022)

VISHNU PRIYA P M 36
How It Works:
1.When you create a car object:

car1 = Car("Model S", 2022)


2.The __init__ method is called automatically:
•Python looks for the __init__ method inside the Car class.
•It sets the model of the car to "Model S", and the year to 2022.

3.Now, the car object car1 has these attributes:


•car1.model is "Model S"
•car1.year is 2022

Why Is This Useful?


The __init__ method allows you to give each car its own specific information when it’s created. Without it, you’d have
to manually assign those values after creating the object, which would be more complicated.
Think of It Like This:
When you order a custom-built car, the factory uses the information you provide (e.g., color, model, year) to build the
car. The constructor (__init__) is like that factory setup process — it ensures that when the car is delivered, it already
has the features you wanted.
VISHNU PRIYA P M 37
CREATING AND IMPORTING AND MODULES IN PYTHON

Creating and importing modules in Python is a fundamental concept for organizing


your code and making it more modular.

Step 1: Create a Module

1. Create a new file and give it a meaningful name with a .py extension. For example,
let's create a module named my_module.py.

2. Inside my_module.py, define functions, classes, or variables that you want to


include in your module. Here's an example:
VISHNU PRIYA P M 38
def greet(name):
return f"Hello, {name}!"

def square(x):
return x ** 2

VISHNU PRIYA P M 39
Step 2: Save the Module

Save the my_module.py file in the same directory as your main script or in a location
where Python can find it (e.g., a directory included in the sys.path list).

Step 3: Import and Use the Module

Now, you can import and use the module in another Python script.

1. Create a new Python script (e.g., main_script.py) in the same directory as the
my_module.py module.

2. Import the module using the import statement:

VISHNU PRIYA P M
import my_module 40
. Use functions from the module in your script:

message = my_module.greet("Alice")
print(message) # Output: Hello, Alice!

result = my_module.square(5)
print(result) # Output: 25

VISHNU PRIYA P M 41
Step 4: Run the Script

Run the main_script.py script using your Python interpreter. You should see the output
corresponding to the imported functions.

Note that you can also use the from ... import ... syntax to import specific functions or
variables from the module directly into your script's namespace:

from my_module import greet

message = greet("Bob")
print(message) # Output: Hello, Bob!

Keep in mind that the name of the module (e.g., my_module) acts as a namespace for the
functions and variables defined within it. This helps prevent naming conflicts between different
modules.
VISHNU PRIYA P M 42
CLASSES AND OBJECTS

Class
A class is a blueprint or template for creating objects. It defines the attributes (data)
and methods (functions) that objects of that class will have. In Python, you define a
class using the class keyword followed by the class name and a colon. The attributes
and methods are defined within
class Dog: the class's body.
def __init__(self, name, age):
self.name = nameself: This is a reference to the current instance of the class. It’s like
saying "this specific dog."
self.age = age

def bark(self):
return "Woof!"

VISHNU PRIYA P M 43
In this example, we've defined a Dog class with attributes name and age, and a method bark()
Object:

An object is an instance of a class. It's a concrete entity that can hold data (attributes)
and perform actions (methods) as defined by the class. To create an object, you call the
class as if it were a function, which creates a new instance of that class.

my_dog = Dog("Buddy", 3)

In this case, my_dog is an object of the Dog class with the name attribute set to "Buddy" and
the age attribute set to 3.

VISHNU PRIYA P M 44
Using Objects:

You can access the attributes and methods of an object using the dot (.) notation:

print(my_dog.name) # Output: Buddy


print(my_dog.age) # Output: 3
print(my_dog.bark()) # Output: Woof!

Constructor (__init__ method):

The __init__ method is a special method called a constructor. It's used to initialize the
attributes of an object when it's created. The self parameter refers to the object itself
and is used to access its attributes and methods.

VISHNU PRIYA P M 45
Methods:

Methods are functions defined within a class. They operate on the attributes of the
object and can perform various actions. Methods often take the self parameter as the
first parameter, which refers to the instance of the class.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
return "Woof!"

def describe(self):
return f"{self.name} is {self.age} years old."

VISHNU PRIYA P M the describe() method provides a way to get a 46

description of the dog.


CLASS PROPERTIES

class properties are attributes associated with a class that have special behavior when
accessed or modified. They provide a way to encapsulate and control the access to
class-level data.
There are two main types of class properties:
class variables and class methods.

VISHNU PRIYA P M 47
Class Variables:
Class variables are shared among all instances of a class. They are
defined within the class scope but outside any methods. Class variables
are accessible using the class name and can also be accessed through
instances of the class. They are often used to store data that is
common to all instances of the class.
(These are variables that are shared among all instances (objects) of a class. Every object can
access and modify this shared variable. It's like having one big notebook that everyone can
read and write in.) class MyClass:
class_variable = 0 # This is a class
variable

def __init__(self, value):


self.instance_variable = value

obj1 = MyClass(10)
VISHNU PRIYA P M
obj2 = MyClass(20) 48

print(obj1.class_variable) # Output: 0
Imagine we are modeling a Car for a vehicle fleet system.

Class Variable: All cars in the fleet might share the same manufacturer.

Class Method: You might want to check how many cars have been added to the fleet.

VISHNU PRIYA P M 49
class Car:
manufacturer = "Tesla" # Class variable (shared by all cars)
total_cars = 0 # Class variable to count the number of cars

def __init__(self, model, year):


self.model = model
self.year = year
Car.total_cars += 1 # Increment the total car count each time a car is created

@classmethod
def fleet_count(cls):
return f"Total cars in the fleet: {cls.total_cars}" # Class method to access the
total number of cars

# Creating instances (objects) of the Car class


car1 = Car("Model S", 2022)
car2 = Car("Model X", 2023)

# Accessing the class variable


print(car1.manufacturer) # Output: Tesla
print(car2.manufacturer) # Output: Tesla
VISHNU PRIYA P M 50

# Accessing the class method to check how many cars are in the fleet
print(Car.fleet_count()) # Output: Total cars in the fleet: 2
Class Methods:
Class methods are methods defined within a class that are bound to the
class rather than instances. They are defined using the @classmethod
decorator and receive the class as their first argument (often named cls
by convention). Class methods are typically used to perform operations
that are related to the class itself rather than instances.
class MyClass:
class_variable = 0

def __init__(self, value):


self.instance_variable = value

@classmethod
def modify_class_variable(cls, new_value):
cls.class_variable = new_value

obj1 = MyClass(10)
obj2 = MyClass(20)

VISHNU PRIYA P M
obj1.modify_class_variable(5) 51
print(obj1.class_variable) # Output: 5
print(obj2.class_variable) # Output: 5
STATIC METHOD
static method is a method that belongs to a class but is not bound to
instances of that class. It's defined within the class, but it doesn't
receive the class or instance as an implicit first parameter (like instance
methods or class methods do). Instead, it behaves like a regular
function, except it's namespaced within the class.
Static methods are typically used for utility functions that are related to
the class in some way but don't depend on or modify instance or class-
specific data. They are defined using the @staticmethod decorator and
do not require access to instance or class-specific information.

VISHNU PRIYA P M 52
class Car: manufacturer = "Tesla" is a class variable. This means every car
manufacturer = "Tesla" we describe using this class will have "Tesla" as its
manufacturer.
@staticmethod
def calculate_efficiency(distance, @staticmethod means that this method doesn’t care
fuel_used): about the specific car. It's just a function that calculates
return distance / fuel_used fuel efficiency.The method takes two inputs:
distance (how far the car has traveled) and fuel_used
(how much fuel was used), then it calculates efficiency
by dividing the distance by the fuel used.
You could illustrate how the method calculate_efficiency doesn't need to know anything about the car instance or the
class, and you can directly call it with data as a utility function.

VISHNU PRIYA P M 53
class MathUtils:
@staticmethod In this example, the add and subtract methods are
def add(x, y): static methods because they don't access any
return x + y instance-specific or class-specific data. They
perform basic arithmetic operations and are
@staticmethod associated with the MathUtils class, but they can
def subtract(x, y): be called using the class name without creating
return x - y instances of the class.

result1 = MathUtils.add(5, 3)
result2 = MathUtils.subtract(10, 2)

print(result1) # Output: 8
print(result2) # Output: 8

VISHNU PRIYA P M 54
CONSTRUCTOR
Constructor is a special method that gets automatically called when an object of a
class is created. It's used to initialize the attributes (properties) of the object. The
constructor method is named __init__ and is defined within the class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

the __init__ method is the constructor for the # Creating objects using the constructor
Person class. It takes two parameters, name and person1 = Person("Alice", 30)
age, and initializes the corresponding attributes of person2 = Person("Bob", 25)
the object being created using those values.
# Accessing object attributes
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
VISHNU PRIYA P M 55

print(person2.name) # Output: Bob


print(person2.age) # Output: 25
A constructor is like a setup method that is automatically called when you create a new
object from a class. It’s used to give your object the basic information it needs as soon as it’s
created. In Python, the constructor is a special method called __init__().
Let’s use the Car example again, but this time we’ll use a constructor to set up important details
about each car when we create it.

class Car:
def __init__(self, model, year):
# This is the constructor method
self.model = model # Set the car's model
self.year = year # Set the car's manufacturing year

__init__(self, model, year): This is the constructor method. It runs automatically when
you create a new car.self.model = model: This means that the model you provide will
be saved as a property of the car.self.year = year: Similarly, the year you provide will
be saved as the car’s manufacturing year.
VISHNU PRIYA P M 56
Key points about constructors in Python:

 The constructor method is named __init__.


 The first parameter of the constructor is conventionally named self,
which refers to the instance being created.
 The constructor is automatically called when an object of the class
is created using the class name followed by parentheses, like a
function call.
 You can pass arguments to the constructor that will be used to
initialize the object's attributes.
 Inside the constructor, you can assign values to attributes using the
self keyword.
 Constructors can have any number of parameters, not just self, and
can perform any necessary initialization.
VISHNU PRIYA P M 57
METHOD OVERRIDING

Method overriding in Python allows a subclass to provide a specific


implementation for a method that is already defined in its parent class.
This enables you to customize the behavior of methods in the subclass
while maintaining the same method signature as the parent class.
Method overriding is a key feature of polymorphism in object-oriented
programming.

VISHNU PRIYA P M 58
How method overriding works

• Method Signature:
To override a method, the subclass method must have the same name
and parameters as the method in the parent class. The method in the
subclass should be defined with the same method signature as the one
in the parent class.(The method in the subclass must have the same
name and parameters as the one in the parent class. This keeps the
method signatures identical so that the subclass method can replace or
extend the functionality of the parent class method.)

• Using the super() Function:


Inside the overridden method of the subclass, you can use the super()
function to call the corresponding method of the parent class. This
allows you to extend or modify the behavior of the parent class method
VISHNU PRIYA P M 59

without completely replacing it.


class Animal:
def speak(self):
return "Animal speaks"
the speak method is overridden in both the Dog
class Dog(Animal): and Cat classes. Each subclass provides its own
def speak(self): implementation of the method, allowing them to
return "Woof" exhibit different behaviors while sharing the same
method name.
class Cat(Animal):
def speak(self):
return "Meow"

animal = Animal()
dog = Dog()
cat = Cat()

print(animal.speak()) # Output: Animal speaks


print(dog.speak()) # Output: Woof
print(cat.speak())
VISHNU PRIYA P M
# Output: Meow 60
Key points about method overriding :

 Method overriding allows a subclass to provide a custom


implementation for a method defined in its parent class.
 The subclass method must have the same name and parameters as
the method in the parent class.
 The super() function is used to call the parent class method within
the overridden method.
 Overriding methods enables you to achieve polymorphism, where
objects of different subclasses can be treated uniformly through
their common interface (method names).
 Overriding methods in Python is a way to implement the "Liskov
Substitution Principle," which is one of the SOLID principles of
object-oriented design.
VISHNU PRIYA P M 61
super()

class Animal(object):
def __init__(self, animal_type):
print('Animal Type:', animal_type)

class Mammal(Animal):
def __init__(self):

# call superclass
super().__init__('Mammal')
print('Mammals give birth directly')

dog = Mammal()

# Output: Animal Type: Mammal


# Mammals give birth directly

VISHNU PRIYA P M 62
INHERITANCE

Inheritance is a fundamental concept in object-oriented


programming (OOP) that allows you to create a new class
(subclass or derived class) based on an existing class
(superclass or base class). The new class inherits attributes
and methods from the existing class, and you can also add
new attributes and methods or override existing ones in the
subclass. Inheritance promotes code reuse, modularity, and
the organization of code into a hierarchy.

you can create a subclass by defining a new class and


VISHNU PRIYA P M 63

specifying the superclass in parentheses after the class


class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return "Animal speaks"

class Dog(Animal): Animal is the base class, and Dog and Cat are
def speak(self): subclasses that inherit from Animal. The
return "Woof" subclasses override the speak method to provide
their own implementations, while still inheriting
class Cat(Animal): the __init__ method and attribute from the Animal
def speak(self): class.
return "Meow"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.name) # Output: Buddy


print(dog.speak()) # Output: Woof
VISHNU PRIYA P M 64

print(cat.name) # Output: Whiskers


print(cat.speak()) # Output: Meow
Key points about inheritance in Python:

 The base class is also known as the superclass or parent class.


 The derived class is also known as the subclass or child class.
 The subclass inherits attributes and methods from the superclass.
 You can add new attributes and methods to the subclass, or override
existing ones.
 Inheritance supports the "is-a" relationship, where a subclass is a
specific type of the superclass.
 Python supports multiple inheritance, allowing a class to inherit from
multiple parent classes.
 The super() function is commonly used to call methods from the
parent class within overridden methods.
 Inheritance promotes code reuse, modularity, and the creation of
hierarchical class structures.
VISHNU PRIYA P M 65
OPERATOR OVERLOADING

Operator overloading refers to the ability to define custom behavior for


standard operators (+, -, *, /, etc.) when used with objects of user-
defined classes. This allows you to make your objects behave more like
built-in types, providing a more intuitive and natural interface.
To overload an operator for a user-defined class, you need to define
special methods with specific names that Python recognizes. These
methods are also called "magic methods" or "dunder methods" (short
for "double underscore" methods). They have names that start and end
with double underscores, such as __add__ for the addition operator.

VISHNU PRIYA P M 66
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):


if isinstance(other, Point):
return Point(self.x + other.x, self.y +
other.y)
else:
raise TypeError("Unsupported operand
type")
we've overloaded the + operator by defining the
def __str__(self): __add__ method in the Point class. When the +
return f"({self.x}, {self.y})" operator is used between two Point objects, the
__add__ method is called, and we perform addition
# Create points element-wise on the x and y coordinates.
p1 = Point(1, 2)
p2 = Point(3, 4)
VISHNU PRIYA P M 67

# Use the overloaded + operator


result = p1 + p2
INTRODUCTION TO PIP

pip is the package installer for Python. It's a command-line tool that allows you to
install and manage Python packages, which are pre-written libraries or modules that
provide specific functionality and can be easily reused in your own projects. Python
packages are typically published and shared on the Python Package Index (PyPI), a
repository of open-source Python packages.

VISHNU PRIYA P M 68
1. Installation:
If you're using a recent version of Python (Python 2.7.9+ or Python 3.4+), pip is
usually already installed. You can check if pip is installed by running pip --version in
your terminal. If it's not installed, you can install it by following the instructions on the
official pip documentation.
2. Installing Packages:
To install a Python package using pip, you use the command pip install
package_name. For example, to install the popular requests package, you would run:
pip install requests

3. Listing Installed Packages:


You can list the packages installed in your Python environment using the command:
pip list

4. Uninstalling Packages:
To uninstall a package, you use the command pip uninstall package_name
VISHNU PRIYA P M 69

pip uninstall requests


5. Specifying Package Versions:
You can specify a particular version of a package to install by including the version number
after the package name. For example:
pip install requests==2.25.1

6. Requirements Files:
You can create a requirements.txt file listing all the packages required for your project, along
with their versions. This is useful for sharing project dependencies with others or for recreating
the same environment later. You can generate a requirements file using:

pip freeze > requirements.txt

VISHNU PRIYA P M 70
7. Installing from a Requirements File:

To install packages from a requirements file, you use the command:

pip install -r requirements.txt

8. Upgrading Packages:
To upgrade a package to the latest version, use the command:

pip install --upgrade package_name

9. Searching for Packages:


You can search for packages on PyPI using the command:
pip search search_term

VISHNU PRIYA P M 71
10. Virtual Environments:
It's recommended to use virtual environments to isolate your
project's dependencies from the system-wide Python
installation. You can create a virtual environment using venv
(for Python 3.3+) or virtualenv (for earlier versions).

pip is a powerful tool that simplifies the process of managing


Python packages and their dependencies, making it easier to
work on projects that rely on various external libraries. It's a
standard tool used by Python developers for creating
consistent and reproducible development environments.
VISHNU PRIYA P M 72

You might also like