» Quick Introduction to Python » 3. Advanced » 3.2 Decorators

Decorators

A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod() as we saw in last section.

A decorator takes a function as input, adds some functionality to it, and then returns the augmented new function.

Construct a Decorator

def bigger(func):
    def augmented_func():
        print("Bigger", end=" ")
        func()
    return augmented_func

Apply Decorator To a Function

@bigger
def show_fruit():
    print("Apple is great!")

show_fruit() # Bigger Apple is great!

Apply Decorator To a Function with Arguments

def bigger(func):
    def augmented_func(*args, **kwargs):
        print("Bigger", end=" ")
        func(*args, **kwargs)
    return augmented_func

@bigger
def show_fruit(name, adjective):
    print(f"{name} is {adjective}!")

show_fruit("Orange", "Sweeter") # Bigger Orange is Sweeter!

Code Challenge

Try to modify the decorator code provided in the editor to make it print --------------- LiteRank! ---------------.

Loading...
> code result goes here
Prev
Next