import time
def f1():
#print(time.time())#>>> 1542357939.895075
print('This is a function')
f1()
#>>> This is a function
def f2():
print('This is a function')
def print_current_time(func):
print(time.time())
func()
print_current_time(f1)
print_current_time(f2)
修改代码时函数对修改是封闭的,对扩展是开放的
unix 时间戳:
Unix 时间戳(Unix timestamp),或称Unix时间(Unix time)
POSIX时间(POSIX time),是一种时间表示方式
定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数
输出结果:
This is a function
1542359549.3405
This is a function
1542359549.354429
This is a function
上述代码评价:
通过print_current_time函数使得上面两个函数增加打印时间的功能
print_current_time函数的作用等同于:
print(time.time())
f1()
print(time.time())
f2()
使用装饰器解决(内聚性更高)
下面给出装饰器完整版
f5类型更全面,装饰器完成的基础上优先考虑f5的实现(灵活)
def decorator(func):#装饰
def wrapper(*args,**kw):#封装 *args可变参数 **kw关键字参数(kw自己指定)
print(time.time())
func(*args,**kw)#函数定义时都可以使用这中方法,不用考虑参数的数量问题
return wrapper
@decorator
def f3(func_name):
print('This is a function'+func_name)
#f=decorator(f1)
#f()#f相当于函数,这里相当于调用decorator()函数
#<==>@decorator使用后可以直接调用f3和f4
f3(' test func')
#>>>1542359549.373817
#>>>This is a function test func
@decorator使用后可以直接调用f5
推荐使用:func(*args,**kw) 函数定义时都可以使用这中方法,不用考虑参数的数量问题
f4使用可变参数:
@decorator
def f4(func_name1,func_name2):
print('This is a function'+func_name1)
print('This is a function'+func_name2)
f4(' test func1',' test func2')
#>>>1542359932.665969
#This is a function test func1
#This is a function test func2
f5 第三个参数:关键字参数(可任意指定参数的数量):
#f5 第三个参数:关键字参数(可任意指定参数的数量)
@decorator
def f5(func_name1,func_name2,**kw):
print('This is a function'+func_name1)
print('This is a function'+func_name2)
print(kw)
f5(' test func1',' test func2', a=1, b=2, c='123')
#This is a function test func1
#This is a function test func2
#{'c': '123', 'b': 2, 'a': 1}