Python Decorators
You want one line written before a greeting. You will call greet with kai. The first line on the screen will be door. The second line will be hi kai.
def announce(fn):
def wrapped(name):
print("door")
return fn(name)
return wrapped
@announce
def greet(name):
return "hi " + name
print(greet("kai"))
The screen shows two lines. The first line is door. The second line is hi kai. You wrote print(greet("kai")). That call does not start on the return line inside greet. @announce puts wrapped around greet, so greet("kai") runs wrapped first. The print inside wrapped writes door. Then wrapped calls the greeting, and the greeting returns hi kai. The print around greet("kai") writes that second line. The program is done. There is no third line.
door is not the greeting. The greeting is hi kai. If the @announce line were not above greet, print(greet("kai")) would write only hi kai. That program is not this one. This program has @announce, so the first line is door and the second line is hi kai.
You can now put a wrapper around a function so one line runs before the function's own line. The screen is door, then hi kai. The next page writes a type next to a name.
One line before the greeting
The first line is door. The second line is hi kai. door runs because @announce is above greet. The next page writes a type next to a name.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top