0
点赞
收藏
分享

微信扫一扫

python自定义装饰器

被装饰函数带参数或不带参数

# coding=utf8

# 自定义装饰器函数,需使用嵌套函数

import time


def decorator_foo(func):
    def inner_func(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        print('run func cost {}s'.format(time.time() - start_time))
    return inner_func


@decorator_foo
def foo(name, age):
    time.sleep(3)
    print('in foo', name, age)


foo('Tony',13)

装饰器本身带参数

# coding=utf8

# 装饰器带参数,则装饰器函数需定义两层嵌套函数

import time


def decorator_foo(deco_type):
    print('deco_type: ', deco_type)

    def outer_func(func):
        def inner_func(*args, **kwargs):
            start_time = time.time()
            func(*args, **kwargs)
            print('run func cost {}s'.format(time.time() - start_time))

        return inner_func

    return outer_func


@decorator_foo(deco_type=1) # 装饰器带参数
def foo(name, age):
    time.sleep(3)
    print('in foo', name, age)


foo('Tony', 13)

被装饰函数带返回值

# coding=utf8

# 被装饰器装饰的函数,带返回值

import time


def decorator_foo(deco_type):
    print('deco_type: ', deco_type)

    def outer_func(func):
        def inner_func(*args, **kwargs):
            start_time = time.time()
            ret = func(*args, **kwargs)
            print('run func cost {}s'.format(time.time() - start_time))
            return ret

        return inner_func

    return outer_func


@decorator_foo(deco_type=1) # 装饰器带参数
def foo(name, age):
    time.sleep(3)
    print('in foo', name, age)
    return name


print(foo('Tony', 13))

举报

相关推荐

0 条评论