Python Tutorial: Decorator Pattern 🎯

beginner
5 min

Python Tutorial: Decorator Pattern 🎯

Welcome to CodeYourCraft! Today, we're diving into the fascinating world of Python Decorators. Let's get started! 🎉

What are Decorators? 📝

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.

Why Decorators? 💡

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.

How to Create a Decorator? 🎯

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:

python
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.

Practical Example 💡

Let's create a decorator that logs the time taken by a function to execute:

python
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))

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is the purpose of a decorator in Python?

Stay tuned for more exciting lessons on Python! Happy coding! 🚀