Decorators
Python · Unit 21: Advanced Python
- Full plan
- Python
- 8 exercises
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. Predict the output
What does this code print?
2. Complete the code
Fill in the blank so the decorator hands back double whatever the function returns.
3. Predict the output
What does this code print?
4. Find the bug
It should print 30, the price times 2. Which line has the error?
5. Complete the code
Fill in the blank so
greetdoesn't lose its name.6. Put the lines in order
Put the lines in order so
greetreturns the greeting in capitals.7. Multiple choice
What does the
@shoutline in this code mean?8. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.