python 入坑路--装饰器(语法糖)中高潮

在小高潮中仅仅实现了,基本的装饰器功能,即添加了新功能。如果传入的函数带有参数,需要返回更多信息如何是好。

 1 import time
 2 def timer(func):
 3     def wrapper():
 4         start_t=time.time()
 5         func()
 6         stop_t=time.time()
 7         print("func run time is {}".format(stop_t-start_t))
 8     return wrrapper
 9 
10 @timer
11 def bar(name):
12     time.sleep(2)
13     print("hello {}".format(name))
14 name="niubi"
15 #输出结果出错 ,看来装饰器不起作用,牛逼不起来了。
16 Traceback (most recent call last):
  File "D:/python_51cto/day4/deco1.py", line 16, in <module>
    bar("niubi")
TypeError: wrrapper() takes 0 positional arguments but 1 was given
 1 import time
 2 def timer(func):
 3     def wrapper(name):
 4         start_t=time.time()
 5         func(name)
 6         stop_t=time.time()
 7         print("func run time is {}".format(stop_t-start_t))
 8     return wrrapper
 9 
10 @timer
11 def bar(name):
12     time.sleep(2)
13     print("hello {}".format(name))
14 
15 name="niubi"
16 bar(name)
17 #输出结果如下   但是不能每次函数参数修改,都要修改装饰器,因为装饰可能装饰很多函数,so ,想到了 *args,**kwargs 非固定参数
18 D:\python_51cto\venv1\Scripts\python.exe D:/python_51cto/day4/deco1.py
19 hello niubi
20 func run time is 2.0001144409179688
21 
22 Process finished with exit code 0
#最正确如下 ,还有 func 参数也可以 return 一些信息。如下例子。据说这样就能满足80% 的需求,还有高高潮等待下回分解。
import time
def timer(func):
    def wrapper(*args,**kwargs):
        start_t=time.time()
        res=func(*args,**kwargs)
        stop_t=time.time()
        print("func run time is {}".format(stop_t-start_t))
        print("----没什么好写的,就写这样了。。。。")
        return res

    return wrrapper

@timer
def bar(name):
    time.sleep(2)
    print("hello {}".format(name))

name="niubi"
bar(name)

 

 

posted @ 2017-12-31 23:46  东郭仔  阅读(359)  评论(0)    收藏  举报