Decorators

  • Learn how decorators extend function behavior in Python using clean and reusable patterns.

  • What is a Decorator?

    A decorator is a function that adds extra functionality to another function without changing its original code.

    👉 In short:
    Decorator = function that modifies another function

    Why We Use Decorators

    Decorators are used to:

    1. Avoid code repetition

    2. Add common functionality to many functions

    3. Keep code clean and readable

    4. Separate logic (main work vs extra work)

    5. Improve maintainability

    Real-Life Example

    Movie Theater Entry

    • Movie = original function

    • Security check = decorator

    Everyone must pass security before entering, but the movie itself does not change.

    How Decorators Work (Simple Idea)

    Decorator

       ↓

    Function

       ↓

    Extra work + Original work

Simple Function Decorator

This decorator prints a message before calling the original function.

def my_decorator(func):
    def wrapper():
        print("Before function execution")
        func()
    return wrapper

@my_decorator
def hello():
    print("Hello Student")

hello()

Login Check Using Decorator

This decorator checks login before allowing access to a page.

def login_required(func):
    def wrapper():
        print("Checking login...")
        func()
    return wrapper

@login_required
def dashboard():
    print("Welcome to Dashboard")

dashboard()
  • Real-Life Mapping

    • Dashboard = main function

    • Login check = decorator