Python Decorators Simplified: A Beginner-Friendly Guide

 

 

 

📌 Introduction

Python decorators are a powerful feature that allows you to modify the behavior of a function without changing its code.
They are widely used in frameworks like Flask and Django, and can help make your code more concise, reusable, and elegant.

🎯 Objective

By the end of this tutorial, you will:

  • Understand what a decorator is in Python
  • Know how to write and apply a decorator
  • Be able to run a simple Python program that demonstrates decorator functionality

🧑‍💻 Sample Python Decorator Code


def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello, world!")

say_hello()
    

📖 Explanation of the Program

Here’s what each part of the code does:

  • my_decorator(func): This is the decorator function. It takes another function as an argument.
  • wrapper(): A nested function that adds behavior before and after the original function call.
  • @my_decorator: This is Python’s decorator syntax. It applies my_decorator to the say_hello function.
  • say_hello(): When this function is called, it now runs with the added behavior from the decorator.

🚀 How to Run This Program

  1. Open your favorite text editor or IDE (e.g., VSCode, PyCharm).
  2. Copy and paste the code into a file named decorator_example.py.
  3. Open a terminal and navigate to the folder containing your file.
  4. Run the program using the command: python decorator_example.py
  5. You will see output showing messages before and after the actual function call.

 

© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *