Python
  • index
  • Basic - 1
  • Basic - 2
  • SQLAlchemy
  • Decorator
  • @property
  • __dict__
  • pathlib
  • class
  • flask
  • Jupyter Notebook
  • PyQt
  • UD - FLASK - PY Basic
  • UD - FLASK - REST
  • UD - FLASK - vanilla SQL
  • UD - FLASK - SQLAlchemy
  • UD - FLASK - JWT
  • UD - FLASK - Serialization
Powered by GitBook
On this page
  • 1. Callable
  • 2. Decorator
  • 3. Another example

Was this helpful?

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()
PreviousSQLAlchemyNext@property

Last updated 5 years ago

Was this helpful?