Python Decorators and Closures 1 — Questions and Answers
Question 1: What is a decorator in Python?
- A function that modifies or extends the behavior of another function (Correct answer)
- A class attribute that defines object appearance
- A special comment syntax for documentation
- A built-in function for string formatting
Correct answer: A function that modifies or extends the behavior of another function
A decorator is a function that takes another function as input and returns a modified or extended version of it.
Question 2: Which symbol is used in Python's decorator syntax?
- #
- $
- @ (Correct answer)
- &
Correct answer: @
The @ symbol placed before a function definition applies the decorator to that function.
Question 3: What does functools.wraps do when used inside a decorator?
- Speeds up the decorated function
- Copies the original function's metadata (like __name__ and __doc__) to the wrapper (Correct answer)
- Prevents the decorator from being applied multiple times
- Automatically logs all function calls
Correct answer: Copies the original function's metadata (like __name__ and __doc__) to the wrapper
functools.wraps preserves the original function's metadata such as its name and docstring, which would otherwise be replaced by the wrapper function's metadata.
Question 4: What is a closure in Python?
- A function that closes all open file handles
- A function that captures and remembers variables from its enclosing scope (Correct answer)
- A way to define private class methods
- A built-in error handling mechanism
Correct answer: A function that captures and remembers variables from its enclosing scope
A closure is an inner function that remembers the values from its enclosing scope even when execution has moved outside that scope.
Question 5: What will the following code print? def outer(): x = 10 def inner(): return x return inner f = outer() print(f())
- None
- Error: x is not defined
- 10 (Correct answer)
- outer
Correct answer: 10
The inner function forms a closure over variable x from the outer function's scope, so it can access and return x even after outer has finished executing.
Question 6: What does the @property decorator do in Python?
- Makes a method private
- Allows a method to be accessed like an attribute (Correct answer)
- Creates a class-level variable
- Converts a method to a static method
Correct answer: Allows a method to be accessed like an attribute
The @property decorator allows you to define methods that can be accessed like attributes, enabling getter behavior without explicit method calls.
Question 7: Which of the following is NOT a built-in Python decorator?
- @staticmethod
- @classmethod
- @property
- @private (Correct answer)
Correct answer: @private
@private is not a built-in Python decorator; Python does not have built-in access modifier decorators, though @staticmethod, @classmethod, and @property are all built-in.
What is a decorator in Python?