Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Closures | Variable Scope
Intermediate Python Techniques
course content

Contenido del Curso

Intermediate Python Techniques

Intermediate Python Techniques

1. Packing and Unpacking
2. Arguments in Function
3. Function as an Argument
4. Variable Scope
5. Decorators

bookClosures

Python closures occur when an inner function is wrapped inside an outer function, effectively referencing a value from the outer scope. They're useful for circumventing global variables.

Closures are useful when you have a few methods to use but not enough to make a whole class. They help keep things simple and clean. But, if you have a lot of methods and attributes to manage, it's better to use a class instead.

Let's look at some examples to understand this better.

12345678910111213
def calculate_income(percent): def annual_income(amount): return amount * percent / 100 return annual_income # function returned by outer function interest_rate_3 = calculate_income(3) # function assigned to the variable interest_rate_7 = calculate_income(7) print(interest_rate_3(1500)) print(interest_rate_3(2000)) print(interest_rate_7(1500)) print(interest_rate_7(2000))
copy

This function calculates annual income for a cash deposit. The closure functionality allows us to store a function in a variable with a specific percentage value, enabling us to reuse it multiple times.

In summary, closures allow you to create and return functions that "remember" values from their enclosing scope, and this is especially useful for creating specialized functions with predefined behavior based on certain parameters.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 6
some-alt