Python Closures Explained | What are Closures in Python | Python Closures
swethadoddamani
137 views
12 slides
Oct 21, 2021
Slide 1 of 12
1
2
3
4
5
6
7
8
9
10
11
12
About This Presentation
In this video you will learn what is Python Closures and why do we need it.
Size: 1.26 MB
Language: en
Added: Oct 21, 2021
Slides: 12 pages
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.