python---装饰器

基础知识

*args and **kwargs in Python

*args

# Python program to illustrate   
# *args for variable number of arguments 
def myFun(*argv):  
    for arg in argv:  
        print (arg) 
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') 

输出:

Hello
Welcome
to
GeeksforGeeks

从中可以看出*argv接受可变参数。它是一个tuple。

# Python program to illustrate   
# *kargs for variable number of keyword arguments 
  
def myFun(**kwargs):  
    for key, value in kwargs.items(): 
        print ("%s == %s" %(key, value)) 
  
# Driver code 
myFun(first ='Geeks', mid ='for', last='Geeks') 

*kwargs

# Python program to illustrate   
# *kargs for variable number of keyword arguments 
  
def myFun(**kwargs):  
    for key, value in kwargs.items(): 
        print ("%s == %s" %(key, value)) 
  
# Driver code 
myFun(first ='Geeks', mid ='for', last='Geeks')

输出:

last == Geeks
mid == for
first == Geeks

关键字参数,它是一个字典。

Using *args and **kwargs to call a function

def myFun(arg1, arg2, arg3): 
    print("arg1:", arg1) 
    print("arg2:", arg2) 
    print("arg3:", arg3) 
      
# Now we can use *args or **kwargs to 
# pass arguments to this function :  
args = ("Geeks", "for", "Geeks") 
myFun(*args) 
  
kwargs = {"arg1" : "Geeks", "arg2" : "for", "arg3" : "Geeks"} 
myFun(**kwargs) 

输出:

arg1: Geeks
arg2: for
arg3: Geeks
arg1: Geeks
arg2: for
arg3: Geeks

foo(*args, **kwargs)

def foo(*args, **kwargs):
    print('args=',args)
    print('kwargs=',kwargs)

输出

foo('a',1,None,a=1,b='2',c=3) ## args= ('a', 1, None) kwargs= {'a': 1, 'b': '2', 'c': 3}
foo(1,2,3,d='4',e=5)  ## args= (1, 2, 3)  kwargs= {'d': '4', 'e': 5}

可以看出,*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个dict

装饰器

一个简单的例子:
python---装饰器_第1张图片

#在函数前加一个装饰器
@log
def now():
	...

就相当于一个嵌套函数now = log(now),因此用装饰器这个功能就好像你在执行一个函数的时候可以给这个加点修饰,比如测试一下这个函数的名字、执行时间啊。(个人感悟)

def log(text):
    def decorator(func):
        def wrapper(*args,**kw):
            t1 = time.time()
            print("%s %s():" %(text,func.__name__))
            return func(*args,**kw)
        return wrapper
    return decorator

@log("execute")
def now_text():
    print('2019-9-20')
    ## 相当于now_text() = log("execute")(now_text)
now_text()

输出:

execute now_text():
2019-9-20

记录函数运行的时间

def metric(func):
    @functools.wraps(func)
    def wrapper(*args, **kw):
        t1=time.time()
        r=func(*args, **kw)
        print('%s excute in %s ms' %(func.__name__, 1000*(time.time()-t1)))
        return r
    return wrapper

# 测试
@metric
def fast(x, y):
    time.sleep(0.0012)
    return x + y;

@metric
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z;

f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
    print('测试失败!')
elif s != 7986:
    print('测试失败!')

参考

  1. https://www.geeksforgeeks.org/args-kwargs-python/
  2. https://www.liaoxuefeng.com/wiki/1016959663602400/1017451662295584
  3. 什么是 *args和**kwargs?https://www.cnblogs.com/fengmk2/archive/2008/04/21/1163766.html
  4. https://blog.csdn.net/jiaowosiye/article/details/79272721

你可能感兴趣的:(python,装饰器)