Python Closures Explained | What are Closures in Python | Python Closures

swethadoddamani 137 views 12 slides Oct 21, 2021
Slide 1
Slide 1 of 12
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12

About This Presentation

In this video you will learn what is Python Closures and why do we need it.


Slide Content

Closures in Python

Agenda 03 Example 01 Prerequisite 04 Use case 02 Definition

Prerequisite

Prerequisite First class function First class functions allows us to treat functions as any other objects, so that we can use them to: pass as an argument to another function r eturn the function from another function assign the function to another variable Nested function Python supports the concept of a "nested function" or "inner function", which is simply a function defined inside another function. Note: Not to be confused with recursive functions

Definition

Definition Closure is an inner function that remembers and has access to the variables in the local scope in which it was created even after the outer function has finished executing. A closure closes over their free variable from their environment

Example

Use case

Use case To replace the unnecessary use of class: Suppose you have a class that contains just one method besides the __ init __ method. In such cases, it is better to use a closure instead of a class. To avoid the use of the global scope: If you have global variables which only one function in your program will use, think closure. Define the variables in the outer function and use them in the inner function. To implement data hiding: The only way to access the enclosed function is by calling the enclosing function. There is no way to access the inner function directly. To remember a function environment even after it completes its execution: You can then access the variables of this environment later in your program.

Further Learning..

Further Learning

India: +91-7022374614 US: 1-800-216-8930 (TOLL FREE) [email protected] 24/7 Chat with Our Course Advisor