python装饰器

import time
def f1():
print(time.time())
print(‘This is what it is’)
#unix 时间戳
#对修改是封闭的,对拓展是开放的
#(不更改原来已经写好的类和函数,用拓展函数或者类来满足新的需求)

def f2():
print(‘this is a function’)

def print_time(func)
print(time.time())
func()

print_time(f2) #没有对f2进行更改,
也可以写作

print(time.time())
f2()

上述概念中,没有装饰器的概念,虽然满足了
修改是封闭的,拓展是开放的这一原则,
但是这个print_time方法实际上并不能真正算作是f2运行时的时间,而是单独添加了一个print_time的功能来近似f2()的unix时间戳

装饰器模式

import time
def decorator(func):
	def wrapper(*args,**kw): 
	#因为装饰器要满足不同函数的使用需求
	#不同函数可能传入参数的数量不同,和类型不同,
	#所以要添加*args 和 **kw(args和kw字样可换,命名无所谓)
	# *args 从而传递0个或多个参数能可以使用
	# **kw 从而可以传递关键字参数
		print(time.time())
		func(*args,**kw)
	return wrapper
	
@decorator
def f1():	
	print('This is what it is')
	
@decorator
def f2(func_name):
	print('This is what it is' + func_name)
	
@decorator
def f3(func_name,func_name1):
	print('This is what it is' + func_name+func_name1)
	
@decorator
def f4(func_name,func_name1,**kw):
	print('This is what it is' + func_name+func_name1)
	print(kw)
f4('sdverg','sdrgdrg',a=1,b=2,c='1234')
#没有改变f1(),但是实现了调用f1()的同时打印时间的功能,只需要一个@decorator  @别的也行

副作用

@decorator
def f1():
	print(f1.__name__)
f1()
#输出结果为
时间戳1507955567.4567892
wrapper(而不是f1)
#函数名称被改成了装饰器的wrapper闭包函数
#从而会引发错误例如我想查看f1()的help文档
print(help(f1))
#就会打印wrapper而不是f1的注释文档

#解决办法就是
from functools import wraps
import time
def decorator(func):
	@wraps(func) #加上这个
	def wrapper(*args,**kw): 
		print(time.time())
		func(*args,**kw)
	return wrapper

你可能感兴趣的:(聚沙成塔,python)