Python Programming - Decorators

Exercise : Decorators - General Questions
  • Decorators - General Questions
1.
How does the @property decorator differ from regular methods in a Python class?
It defines a read-only property without a setter method
It marks a method as a class method
It is used to create private methods
It enables dynamic method invocation
Answer: Option
Explanation:
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.

2.
Which of the following decorators is used to cache the result of a function to improve performance?
@staticmethod
@property
@functools.lru_cache
@classmethod
Answer: Option
Explanation:
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.

3.
What does the @wraps decorator do?
Marks a method as a static method
Provides a way to document and maintain the original function's metadata
Converts a method to a class method
Indicates a method is an instance method
Answer: Option
Explanation:
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.

4.
Which built-in decorator is used to enforce that a function is only called once?
@staticmethod
@functools.lru_cache
@functools.singledispatch
@functools.singledispatchmethod
Answer: Option
Explanation:
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.

5.
What happens when you use the @classmethod decorator on a method in a Python class?
Marks the method as a static method
Converts the method to a class method
Indicates the method is an instance method
Decorates the method with dynamic behavior
Answer: Option
Explanation:
The @classmethod decorator is used to convert a method into a class method, allowing it to access and modify class-level attributes, rather than instance-level attributes.