Exercise: Python

Questions for: Decorators

Which decorator is used to declare abstract methods in a Python class?
A:
@abstractmethod
B:
@staticmethod
C:
@classmethod
D:
@property
Answer: A
The @abstractmethod decorator is used to declare abstract methods in an abstract base class, indicating that concrete subclasses must implement these methods.
What does the @staticmethod decorator do when applied to a method inside a class?
A:
Converts the method to a class method
B:
Marks the method as a static method
C:
Indicates the method is an instance method
D:
Decorates the method with dynamic behavior
Answer: B
The @staticmethod decorator is used to mark a method as a static method within a class, indicating that it belongs to the class and not to an instance.
Which decorator is commonly used for memoization in Python and can be applied to instance methods?
A:
@staticmethod
B:
@functools.lru_cache
C:
@classmethod
D:
@property
Answer: B
The @functools.lru_cache decorator is commonly used for memoization, caching the results of function calls to improve performance. It can be applied to instance methods as well.
What is the primary purpose of the @contextmanager decorator?
A:
Converts a method to a class method
B:
Creates a context manager for resource management
C:
Marks a method as a static method
D:
Decorates a method with dynamic behavior
Answer: B
The @contextmanager decorator is used to create a context manager, allowing resource allocation and deallocation to be managed using the with statement.
When using the @functools.lru_cache decorator, what is the purpose of the maxsize parameter?
A:
Sets the maximum number of cache entries
B:
Controls the cache eviction policy
C:
Determines the cache timeout duration
D:
Specifies the maximum recursion depth for caching
Answer: A
The maxsize parameter in the @functools.lru_cache decorator specifies the maximum number of entries to be stored in the cache. Once this limit is reached, older entries are evicted.
Ad Slot (Above Pagination)
Quiz