Closures
Sveip for å vise menyen
Closures vs. Nested Functions
A nested function is any function that you define inside another function. Nested functions are useful for organizing code and limiting the scope of helper functions. However, not all nested functions are closures.
A closure is a special type of nested function. Closures are nested functions that "remember" and can access variables from their enclosing function's scope, even after the outer function has finished running. This means closures can maintain state across multiple calls.
Key points:
- All closures are nested functions;
- Not all nested functions are closures;
- A nested function becomes a closure only if it uses variables from the outer function's scope and those variables are still accessible after the outer function has returned.
This distinction is important for understanding how Python manages variable scope and how you can use closures to encapsulate state and behavior together.
12345678910def make_greeter(name): def greet(): return f"Hello, {name}!" return greet greeter = make_greeter("Alice") print(greeter()) another_greeter = make_greeter("Bob") print(another_greeter())
When you call make_greeter("Alice"), Python creates a new greet function that remembers the value of name as "Alice". Even though make_greeter finishes running, the returned greet function still has access to the name variable from its original scope. This is why calling greeter() prints Hello, Alice!, and calling another_greeter() prints Hello, Bob!. Each closure keeps its own copy of the variables it needs.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår