Exercise: Python

Questions for: Decorators

What is the purpose of the @functools.lru_cache decorator's typed parameter?
A:
It enforces strong typing for the cached values.
B:
It uses a different cache for each data type.
C:
It enables caching for functions with different argument types.
D:
It specifies the maximum size of the cache.
Answer: B
The @functools.lru_cache decorator's typed parameter, when set to True, uses a different cache for each distinct data type, preventing collisions between values of different types.
Which decorator is commonly used for rate-limiting function calls?
A:
@functools.ratelimit
B:
@functools.limitrate
C:
@functools.ratelimiter
D:
@functools.limitcalls
Answer: A
There is no built-in @functools.ratelimit decorator in Python, but custom decorators can be created for rate-limiting function calls.
How does the @property decorator differ from the @staticmethod decorator?
A:
@property is used for dynamic property access, while @staticmethod is used for class-level attribute access.
B:
@property is used to define read-only properties, while @staticmethod is used to convert a method to a class method.
C:
@property is used for dynamic method invocation, while @staticmethod is used to indicate a method is an instance method.
D:
@property is used to convert a method to a class method, while @staticmethod is used for dynamic method invocation.
Answer: B
@property is used to define read-only properties without the need for explicit getter methods. @staticmethod is used to mark a method as a static method within a class.
Which decorator is commonly used for retrying a function with a specified delay in case of failure?
A:
@functools.retry
B:
@functools.retry_on_fail
C:
@functools.retriable
D:
@functools.retry_with_delay
Answer: A
There is no built-in @functools.retry decorator in Python, but custom decorators can be created for retrying a function with a specified delay in case of failure.
How does the @staticmethod decorator differ from the @classmethod decorator?
A:
@staticmethod is used for dynamic method invocation, while @classmethod is used for class-level attribute access.
B:
@staticmethod can be called on instances and the class itself, while @classmethod is only callable on instances.
C:
@staticmethod is used to convert a method to a class method, while @classmethod is used to mark a method as a static method.
D:
@staticmethod is used to indicate a method is an instance method, while @classmethod is used for dynamic method invocation.
Answer: B
@staticmethod allows a method to be called on both instances and the class itself, while @classmethod is specifically for class-level attribute access and can only be called on instances.
Ad Slot (Above Pagination)
Quiz