weimingge14
1/16/2018 - 11:53 AM

Python 基础 —— 装饰器语法

Python 基础 —— 装饰器语法

import time


def decorator(func):
    def wrapper(*args, **kw):
        print(time.time())
        func(*args, **kw)

    return wrapper


@decorator
def f1(func_name):
    print('This is a function named {}.'.format(func_name))


@decorator
def f2(func_name1, func_name2):
    print('This is a function named {}.'.format(func_name1))
    print('This is a function named {}.'.format(func_name2))


# **kw 关键字参数
@decorator
def f3(func_name1, func_name2, **kw):
    print('This is a function named {}.'.format(func_name1))
    print('This is a function named {}.'.format(func_name2))
    print('关键字参数', kw)


f1("hello")
f2('Python', 'NumPy')
f3('test func1', 'test func2', a=1, b=2, c=3, d=4)
import time


def decorator(func):
    def wrapper(*args):
        print(time.time())
        func(*args)

    return wrapper


@decorator
def f1(func_name):
    print('This is a function named {}.'.format(func_name))


@decorator
def f2(func_name1, func_name2):
    print('This is a function named {}.'.format(func_name1))
    print('This is a function named {}.'.format(func_name2))


f1("hello")
f2('Python', 'NumPy')