Menu
Coddy logo textTech

Introduction to Decorators

Part of the Object Oriented Programming section of Coddy's Python journey — lesson 9 of 64.

Decorators are a way to modify or enhance functions and classes without changing their original code. They use the @ symbol.

Here is an example of a simple decorator: 

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

Apply the decorator using @:

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

Call the decorated function:

say_hello()

Output:

Before function runs
Hello!
After function runs

The @my_decorator is equivalent to writing:

def say_hello():
    print("Hello!")

say_hello = my_decorator(say_hello)

But the @ syntax is much cleaner and easier to read.

Key Point: Decorators wrap around functions to add extra functionality without modifying the original function code

Cheat sheet

Decorators modify or enhance functions without changing their original code using the @ symbol.

Basic decorator structure:

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

Apply decorator using @:

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

The @my_decorator syntax is equivalent to:

say_hello = my_decorator(say_hello)

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming