装饰器
# 装饰器,特性,注解
# 对修改是封闭的,对扩展是开发的
import time
def print_current_time(func):
print(time.time())
func()
def f1():
print('This is a function-1')
def f2():
print('This is a function-2')
print_current_time(f1)
print_current_time(f2)
#输出结果
#1521624272.8735173
#This is a function-1
#1521624272.992277
#This is a function-2
不修改函数调用方式,依旧可以修改输出
# 对修改是封闭的,对扩展是开发的
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
@decorator
def f1():
print('This is a function-1')
def f2():
print('This is a function-2')
f1()
f2()
#输出结果
#1521637627.8076153
#This is a function-1
#This is a function-2
利用 *args 可以传入任意个参数
# 对修改是封闭的,对扩展是开发的
import time
def decorator(func):
def wrapper(*args):
print(time.time())
func(*args)
return wrapper
@decorator
def f0():
print('This is a function-0 ')
@decorator
def f1(func_name):
print('This is a function-1 ' + func_name)
@decorator
def f2(func_name1, func_name2):
print('This is a function-2 ' + func_name1)
print('This is a function-2 ' + func_name2)
f0()
f1('test')
f2('try', 'try')
#输出结果
#1521639444.4680157
#This is a function-0
#1521639444.4700003
#This is a function-1 test
#1521639444.4730039
#This is a function-2 try
#This is a function-2 try
装饰器的最终形态,**kw 代表关键字参数,多余的关键字会被当作字典打印出来
def decorator(func):
def wrapper(*args, **kw):
print(time.time())
func(*args, **kw)
return wrapper
不破坏代码实现,实现代码复用性,可以多个装饰器堆叠使用
网友评论