Exercise: Python

Questions for: Decorators

How does the @functools.singledispatch decorator differ from @functools.singledispatchmethod?
A:
@functools.singledispatch is used for functions, while @functools.singledispatchmethod is used for methods.
B:
@functools.singledispatch is used for static methods, while @functools.singledispatchmethod is used for instance methods.
C:
@functools.singledispatch is used for class-level attribute access, while @functools.singledispatchmethod is used for dynamic method invocation.
D:
There is no difference; they serve the same purpose.
Answer: A
@functools.singledispatch is used for functions, providing a mechanism for function overloading based on argument types, while @functools.singledispatchmethod serves the same purpose but is specifically designed for methods within a class.
What does the @functools.cached_property 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:
Caches the result of the method and returns the cached value
D:
Decorates the method with dynamic behavior
Answer: C
The @functools.cached_property decorator caches the result of a method and returns the cached value on subsequent calls.
What is the purpose of the @functools.singledispatchmethod decorator?
A:
Converts a method to a class method
B:
Enables function overloading based on argument types
C:
Marks a method as a static method
D:
Decorates a method with dynamic behavior
Answer: B
The @functools.singledispatchmethod decorator in Python is used to enable function overloading based on the type of the first argument within a class.
What is the purpose of the @functools.retry decorator?
A:
Retries a function with a specified delay in case of failure
B:
Converts a method to a class method
C:
Decorates a method with dynamic behavior
D:
Provides a way to document and maintain the original function's metadata
Answer: A
The @functools.retry decorator is used to retry a function with a specified delay in case of failure.
@functools.retry(max_retries=3, delay=2)
def unstable_function():
    # Function implementation
What is the primary purpose of the @functools.total_ordering decorator?
A:
Converts a method to a class method
B:
Enables automatic generation of rich comparison methods
C:
Marks a method as a static method
D:
Decorates a method with dynamic behavior
Answer: B
The @functools.total_ordering decorator is used to automatically generate rich comparison methods (e.g., __eq__, __lt__) based on a minimal set of comparison methods provided in the class.
@functools.total_ordering
class MyClass:
    def __init__(self, value):
        self.value = value
    
    def __eq__(self, other):
        return self.value == other.value
    
    def __lt__(self, other):
        return self.value < other.value
Ad Slot (Above Pagination)
Quiz