Decorators and Closures Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Decorators and Closures flashcards as text
What does @staticmethod mean when applied to a method inside a class?
Answer: The method receives no implicit first argument — no self or cls
@staticmethod indicates the method does not receive an implicit first argument, making it essentially a regular function that belongs to the class's namespace.
What is the key difference between @classmethod and @staticmethod?
Answer: @classmethod receives the class as its first argument (cls), @staticmethod receives no implicit argument
@classmethod receives the class itself as its first argument (conventionally called cls), while @staticmethod receives no implicit first argument at all.
What is the output of the following code? def make_multiplier(n): def multiplier(x): return x * n return multiplier double = make_multiplier(2) triple = make_multiplier(3) print(double(5), triple(5))
Answer: 10 15
double closes over n=2 and triple closes over n=3; each closure independently remembers its own captured value of n, so double(5) returns 10 and triple(5) returns 15.
What is a common use of decorators in Python web frameworks like Flask?
Answer: Route registration — mapping URLs to handler functions with @app.route
In Flask, decorators like @app.route('/path') register URL routes to handler functions, which is one of the most widespread real-world applications of decorators.
What happens to a decorated function if you do not use functools.wraps inside the wrapper?
Answer: The wrapped function loses its original metadata such as __name__ and __doc__
Without functools.wraps, the wrapper function's metadata (like __name__ and __doc__) replaces the original function's metadata, which causes problems with debugging and introspection tools.
Which description best defines memoization as implemented with a decorator?
Answer: A decorator that caches function results keyed by arguments to avoid redundant computation
Memoization is a technique where a decorator caches the results of function calls keyed by their arguments, so repeated calls with the same arguments return cached results without recomputing.
Which built-in Python module provides the lru_cache decorator for automatic memoization?
Answer: functools
functools.lru_cache is a built-in decorator that implements memoization with a Least Recently Used eviction strategy to limit cache size.