Python Programming - Decorators
Exercise : Decorators - General Questions
- Decorators - General Questions
1.
How does the
@property
decorator differ from regular methods in a Python class?
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?
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?
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?
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?
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.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers