Python

 

 

 

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

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)