Advanced Python Development Course
Chapter
>
Level
Decorators
Optimizing Decorators
Objective
Collect ingredients and prepare different types of pizza’s by using decorators.
Now that the ovens have been set up, it’s time to prepare some pizzas so we can cook them later. Now that we know how to use decorators we can work to optimize them a bit. By using the @ symbol in code followed by the name of the decorator and place this code above the decorated function, we can automatically attach a decorator without using a variable. For example:
# Decorator
def create_pizza(func):
def set():
pizza = ["dough","red sauce","cheese"]
player.combine(pizza)
func()
return set
# Function being decorated with @
@create_pizza
def peperoni_pizza():
player.place("Peperoni")
player.speak("Peperoni Pizza has been prepped")
# Using pre-decorated function
peperoni_pizza()
It’s worth noting, this technique simplifies the process by having a function pre-decorated before use, however sometimes you may still wish to assign a decorator to a variable for greater flexibility.
To start off, walk to the gold X mark and grab the ingredients to make pizza. The ingredients for making the pizza are: "cheese", "dough", "red sauce", "peperoni", "ham","olive", "pepper", "onion" and "pineapple" . Most of these ingredients are inside a Matrix representing the pantry shelves, use List Comprehensions to store all the items you wish to grab in a list.
shelves = [ ["cheese", "dough", "jar"], ["jar", "red sauce", "jar"], ["peperoni", "jar" , "ham"], ["olive", "pepper", "onions"] ] ingredients = [ item for row in shelves for item in row if not "jar" in item]
In the above code the list ingredients cycles through the row’s of the Matrix named shelves and removes all items in the Matrix named "jar" . This List Comprehension saves us time from having to manually add everything together. Use the speak() function with the ingredients list to verify the items you’re going to use.
Once all ingredients are collected save for the "pineapple" , the functions to make the pizzas need place() functions added in order to complete their utility. These functions are set up in the code editor and are named: peperoni_pizza() which requires: "peperoni" , vegetable_pizza() which requires: "olive", "pepper", "onion" , and pineapple_pizza() which requires: "ham" and "pineapple".
Walk to the dark X marks and use the decorated functions to prepare the pizzas. On X marks with red carpets create peperoni_pizza() , on green carpets create vegetable_pizza() and on yellow carpets create pineapple_pizza(). On your way to the yellow carpet, stop by the light X mark, face the cabinet and use the collect() function to grab the "pineapple" . Prep all pizzas in order to successfully complete the level.