Decorator

1. Callable

Any object which implements the method __call__() is termed callable.

2. Decorator

  • metaprogramming

  • inside a decorator, define a func and return it.

def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

def percent(func):
    def inner(*args, **kwargs):
        print("%" * 30)
        func(*args, **kwargs)
        print("%" * 30)
    return inner

@star
@percent
def printer(msg):
    print(msg)

printer("Hello")
******************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Hello
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
******************************

其中

@star
@percent
def printer(msg):
    print(msg)

# 等效

def printer(msg):
    print(msg)
printer = star(percent(printer))

3. Another example

import functools  # function tools

def my_decorator(f):
    @functools.wraps(f)
    def function_that_runs_f():
        print("Before!")
        f()
        print("After!")
    return function_that_runs_f

@my_decorator
def my_func():
    print("I'm in the function.")

my_function()

Last updated

Was this helpful?