Welcome to CodeYourCraft! Today, we're diving into the fascinating world of Python Decorators. Let's get started! 🎉
Decorators in Python are a design technique that allows you to add new functionality to an existing object (function or class) without modifying its source code. They are a powerful tool that helps in writing reusable and modular code.
Decorators help in organizing code, making it more readable, and reusable. They can be used for logging, caching, or adding additional behavior to existing functions or classes.
A decorator is a special type of function that takes another function as an argument and returns a new function with added behavior. Let's create a simple example:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
func(*args, **kwargs)
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello, World!")
say_hello()In this example, my_decorator is a decorator that takes the say_hello function as an argument and returns a new function (wrapper). The @my_decorator syntax is used to apply the decorator to the say_hello function.
Let's create a decorator that logs the time taken by a function to execute:
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Time taken by {func.__name__} to execute: {end_time - start_time} seconds")
return result
return wrapper
@timer
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print(factorial(5))What is the purpose of a decorator in Python?
Stay tuned for more exciting lessons on Python! Happy coding! 🚀