Challenge: Decorate Multiple Functions
Decorators in Python are designed to be reusable, meaning you can apply the same decorator to many different functions. This flexibility allows you to add the same behaviorβsuch as logging, timing, or validationβto multiple functions without repeating code. By defining a decorator once and then applying it wherever needed, you keep your codebase clean and consistent. When a decorator is applied to more than one function, each function will receive the additional functionality provided by the decorator, but the core logic of each function remains unchanged. This approach is especially powerful for cross-cutting concerns like debugging or monitoring, where you want to add the same action to various parts of your program.
Swipe to start coding
Create a decorator named log_function_name that logs the name of any function it decorates before the function is called. Apply this decorator to both greet and add. When either function is called, the decorator must print the function's name before executing the function and returning its result.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you show me an example of how to apply the same decorator to multiple functions?
What are some common use cases for decorators in real-world projects?
How do I write my own reusable decorator in Python?
Awesome!
Completion rate improved to 5.88
Challenge: Decorate Multiple Functions
Swipe to show menu
Decorators in Python are designed to be reusable, meaning you can apply the same decorator to many different functions. This flexibility allows you to add the same behaviorβsuch as logging, timing, or validationβto multiple functions without repeating code. By defining a decorator once and then applying it wherever needed, you keep your codebase clean and consistent. When a decorator is applied to more than one function, each function will receive the additional functionality provided by the decorator, but the core logic of each function remains unchanged. This approach is especially powerful for cross-cutting concerns like debugging or monitoring, where you want to add the same action to various parts of your program.
Swipe to start coding
Create a decorator named log_function_name that logs the name of any function it decorates before the function is called. Apply this decorator to both greet and add. When either function is called, the decorator must print the function's name before executing the function and returning its result.
Solution
Thanks for your feedback!
single