Python Programming - Decorators

Exercise : Decorators - General Questions
  • Decorators - General Questions
11.
What is the primary purpose of the @contextmanager decorator?
Converts a method to a class method
Creates a context manager for resource management
Marks a method as a static method
Decorates a method with dynamic behavior
Answer: Option
Explanation:
The @contextmanager decorator is used to create a context manager, allowing resource allocation and deallocation to be managed using the with statement.

12.
Which decorator is commonly used for memoization in Python and can be applied to instance methods?
@staticmethod
@functools.lru_cache
@classmethod
@property
Answer: Option
Explanation:
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.

13.
What does the @staticmethod decorator do when applied to a method inside a class?
Converts the method to a class method
Marks the method as a static method
Indicates the method is an instance method
Decorates the method with dynamic behavior
Answer: Option
Explanation:
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.

14.
Which decorator is used to declare abstract methods in a Python class?
@abstractmethod
@staticmethod
@classmethod
@property
Answer: Option
Explanation:
The @abstractmethod decorator is used to declare abstract methods in an abstract base class, indicating that concrete subclasses must implement these methods.

15.
How does the @staticmethod decorator differ from the @classmethod decorator?
@staticmethod is used for dynamic method invocation, while @classmethod is used for class-level attribute access.
@staticmethod can be called on instances and the class itself, while @classmethod is only callable on instances.
@staticmethod is used to convert a method to a class method, while @classmethod is used to mark a method as a static method.
@staticmethod is used to indicate a method is an instance method, while @classmethod is used for dynamic method invocation.
Answer: Option
Explanation:
@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.