Exercise: Python

Questions for: Decorators

How can you create a decorator that takes arguments?
A:
Using the @staticmethod decorator
B:
Using the @functools.wraps decorator
C:
By defining a higher-order function that returns the actual decorator
D:
By using the @classmethod decorator
Answer: C
To create a decorator that takes arguments, you can define a higher-order function that returns the actual decorator based on the provided arguments.
Which decorator is used to ensure that a function is only executed after a certain condition is met?
A:
@functools.lru_cache
B:
@functools.wraps
C:
@functools.singledispatch
D:
@functools.singledispatchmethod
Answer: D
There is no built-in @functools.singledispatchmethod decorator in Python, but a custom decorator can be created to execute a function based on a specified condition.
What is the primary purpose of the @functools.singledispatch decorator?
A:
Converts a method to a class method
B:
Enables function overloading based on argument types
C:
Indicates a method is an instance method
D:
Decorates a method with dynamic behavior
Answer: B
The @functools.singledispatch decorator in Python is used to enable function overloading based on the type of the first argument.
Which decorator can be used to measure the execution time of a Python function?
A:
@functools.lru_cache
B:
@functools.singledispatch
C:
@functools.wraps
D:
@functools.timer
Answer: D
There is no built-in @functools.timer decorator in Python, but a custom timer decorator can be created using external libraries or by measuring time manually.
What happens when you use the @classmethod decorator on a method in a Python class?
A:
Marks the method as a static method
B:
Converts the method to a class method
C:
Indicates the method is an instance method
D:
Decorates the method with dynamic behavior
Answer: B
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.
Ad Slot (Above Pagination)
Quiz