Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Basic Smores Recipe | Mastering Python Decorators
Intermediate Python Techniques

book
Challenge: Basic Smores Recipe

Oppgave

Swipe to start coding

When you run this script, it should output the layers of a smore in the correct order: cracker, chocolate, marshmallow, cracker.

This exercise demonstrates the concept of how decorators wrap functionality around a function in Python.

  1. In the wrapper function of the crackers decorator, you need to call the function being decorated (i.e., func). This should be done between the two print statements;
  2. Ensure that the function func is called with any arguments and keyword arguments it might receive;
  3. Similar to the crackers decorator, the chocolate decorator should call the function it's decorating.
  4. The main task is to put decorators in right sequence. You must receive:
python
~~cracker~~
-roasted-------marshmallow-
=chocolate=
~~cracker~~

Løsning

def chocolate(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
print(" =chocolate=")
return wrapper

def crackers(func):
def wrapper(*args, **kwargs):
print(" ~~cracker~~")
func(*args, **kwargs)
print(" ~~cracker~~")
return wrapper

@crackers
@chocolate
def basic_smores():
print("-roasted-------marshmallow-")

# Test the recipe
basic_smores()

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 5. Kapittel 6
single

single

def chocolate(___):
def wrapper(*args, **kwargs):
___(___, ___)
print(" =chocolate=")
return wrapper

def crackers(func):
def wrapper(*args, **kwargs):
print(" ~~cracker~~")
___(___, ___)
print(" ~~cracker~~")
return ___

@___
@___
def basic_smores():
print("-roasted-------marshmallow-")

# Test the recipe
basic_smores()

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt