装饰器

有一个函数f1,在不改变函数f1内部代码的情况,让其每次运行时都打印出及时的时间戳
实例:

import time

def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper

@decorator	# 语法糖
def f1():
    print('This is a function')

f1()	# 1569403332.0502675 \ This is a function

优势:没有改变调用方式

有一个或多个函数参数、关键字参数的装饰器的使用
实例:

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 ' + func_name)
    
@decorator
def f2(func_name1, func_name2):
    print('This is ' + func_name1)
    print('This is ' + func_name2)

@decorator
def f3(func_name1, func_name2, **kw):
    print('This is ' + func_name1)
    print('This is ' + func_name2)
    print(kw)

f1('test')		# 1569404249.6017482 \ This is test
f2('test2.1', 'test2.2')	# 1569404249.6017482 \ This is test2.1 \ This is test2.2
f3('test3.1', 'test3.2', a=1, b=2, c='1,2,3')	# 1569404981.3045993 \ This is test3.1 \ This is test3.2 \ {'a': 1, 'b': 2, 'c': '1,2,3'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值