Exercise: Python

Questions for: Decorators

Which built-in decorator is used to enforce that a function is only called once?
A:
@staticmethod
B:
@functools.lru_cache
C:
@functools.singledispatch
D:
@functools.singledispatchmethod
Answer: C
The @functools.singledispatch decorator is used to define a single-dispatch generic function, ensuring that the function is only called once for a particular type.
What does the @wraps decorator do?
A:
Marks a method as a static method
B:
Provides a way to document and maintain the original function's metadata
C:
Converts a method to a class method
D:
Indicates a method is an instance method
Answer: B
The @wraps decorator is used to preserve the original metadata of a function, including its name, docstring, and other attributes, when creating a wrapper or decorator.
Which of the following decorators is used to cache the result of a function to improve performance?
A:
@staticmethod
B:
@property
C:
@functools.lru_cache
D:
@classmethod
Answer: C
The @functools.lru_cache decorator is used to cache the result of a function with the least recently used (LRU) strategy, improving the performance by avoiding redundant calculations.
How does the @property decorator differ from regular methods in a Python class?
A:
It defines a read-only property without a setter method
B:
It marks a method as a class method
C:
It is used to create private methods
D:
It enables dynamic method invocation
Answer: A
The @property decorator is used to define read-only properties in a class. It allows you to access a method as an attribute without the need for explicit getter methods. However, it doesn't provide a setter method, making the property read-only.
Ad Slot (Above Pagination)
Quiz