Skip to the content

Decorators

Python · Unit 21: Advanced Python

You already used two decorators: @dataclass and @property. A decorator is a function that takes another function and hands back a new one in its place.

Without @ the trick is visible: you wrap the function and store the result under the same name.

def shout(f):
    def wrapper():
        return f().upper()
    return wrapper

def greet():
    return "hi"

greet = shout(greet)
print(greet())

Prints

HI

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so the decorator hands back double whatever the function returns.

  3. 3. Predict the output

    What does this code print?

  4. 4. Find the bug

    It should print 30, the price times 2. Which line has the error?

  5. 5. Complete the code

    Fill in the blank so greet doesn't lose its name.

  6. 6. Put the lines in order

    Put the lines in order so greet returns the greeting in capitals.

  7. 7. Multiple choice

    What does the @shout line in this code mean?

  8. 8. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →