The Seven Year Itch.

MENU

python中的装饰器(之前写过一个,太草率不规范)

December 18, 2017 • Read: 281 • Python

2017-12-18<再次对装饰器记录内容进行梳理>

-方法在有参数的情况下

import datetime


def decorator(func):
    def wrapper(*args):
        print(datetime.datetime.utcnow())
        func(*args)

    return wrapper


@decorator
def print_time(a, aa, bb):
    print('success   {}/{}/{}'.format(a, aa, bb))


print_time(1, 2, 3)

-方法和装饰器都带参数

import datetime
def decorator(route): # 装饰器接收的参数
    def wrapper(func): # 接收使用装饰器的方法
        def __wrapper(*args,**kwargs): # 接收方法里面的参数
            print(datetime.datetime.utcnow())
            print(route)
            func(*args,**kwargs)
        return __wrapper
    return wrapper

@decorator('/api/test')
def get_content(a, b, c):
    print('success {}{}{}'.format(a, b, c))


get_content(1, 2, 3)

Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code