12. Python Decorators Flashcards

1
Q

What does a decorator do?

A

Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more “Pythonic”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the basic format of a decorator?

A

def new_decorator(func):

    def wrap_func():
        print("Code would be here, before executing the func")
    func()

    print("Code here will execute after the func()")

return wrap_func
def func_needs_decorator():
    print("This function is in need of a Decorator")
# Reassign func_needs_decorator
func_needs_decorator = new_decorator(func_needs_decorator)

func_needs_decorator()
Code would be here, before executing the func
This function is in need of a Decorator
Code here will execute after the func()

So what just happened here? A decorator simply wrapped the function and modified its behavior. Now let’s understand how we can rewrite this code using the @ symbol, which is what Python uses for Decorators:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the shortcut symbol to use a decorator?

A

@

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you use a decorator using the shortcut symbol?

A
@new_decorator
def func_needs_decorator():
    print("This function is in need of a Decorator")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly