装饰器类似csharp中的特性和java中的注解
import time
def f1():
print(time.time())#打印unix时间戳
print(‘this is a func’)
f1()
#修改封闭,扩展开放
def f2():
print(time.time())
print(‘this is a func’)
def print_current_time(func):#函数可以作为参数传入
print(time.time())
func()
print_current_time(f1)
print_current_time(f2)
装饰器实现:
def decorator():
def wrapper():
print(time.time())
func()
return wrapper
f=decorator(f1)
f()
@decorator
def f1():
print(‘this is a func’)
f1()
#与上相同
#修改wraper和func中的参数为可变参数*args
@decorator
def f2(func1,func2):
非关键字参数的特征是一个星号加上参数名,比如number,定义后,number可以接收任意数量的参数,并将它们储存在一个tuple中。
关键字参数的特征是两个星号** 加上参数名,比如**kw, 定义后,kw将接收到的任意数量参数存到一个dict中。关键字参数是在传递构成中不必按照顺序传递(因为dict内的key-value是没有顺序的),但必须要提供”传递参数名=传递参数值”形式的参数。