Conteúdo do Curso
Intermediate Python: Arguments, Scopes and Decorators
Intermediate Python: Arguments, Scopes and Decorators
Closures
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.
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))
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.
Obrigado pelo seu feedback!