装饰器作为 python 的中的一个功能可以说是非常重要的, 也是学习 python 中的一个门坎, 可能很多人会觉得在学习装饰器的时候很容易会搞迷糊, 最在看 python 核心编程时和 python 之阐时感觉有点明白了, 在此抛砖引玉.
装饰器的作用最大的特点的是, 在不修改原代码的情况下, 给原有的代码附加功能, 所以要写装饰器要遵守二个规则:
不能修改被装饰的函数
不能修改函数的调用方式
想要搞明白装饰器需要的知识点
1. 函数的作用域
2. 闭包
3. 高阶函数
4. 嵌套函数
代码如下:
- def fun(name):
- def wapper():
- print("the test fun is %s" %name)
- return wapper
- a = fun(test) #<function fun.<locals>.wapper at 0x0000000002103840>
- type(a) #<class 'function'>
这里可以看的出来 fun(test) 是一个函数的内存地址, 程序给出了一个函数类型
由此代码也可以看得出一个结论, 就是函数既变量的一个方法, 那么这样的话, 就可以很好的理解装饰的工作形式了
代码如下:
- import time
- def timer(fun):
- def wapper(*args,**kwargs):
- start_time = time.time()
- fun()
- stop_time = time.time()
- func_time = stop_time - start_time
- print('the fun run time is %s' %func_time)
- return wapper
- def test1():
- time.sleep(3)
- print('the fun1 is test1')
- test1= timer(test1)
- print(test1) #<function timer.<locals>.wapper at 0x00000000025B0488>
- test1()
- > the fun1 is test1
>the fun run time is 3.0052061080932617
这里已经实现了我们写装饰器的所要达到的各要求, 并且实现也原代码函数要附加的功能
但是真正的 python 中已经为我们考虑到如 test1 = timer(test1) 的繁琐操作, python 中用 @代替我们所做的操作, 让代码看起来更加的优雅简洁所以正确的代码应该是这样的
- import time
- def timer(fun):
- def wapper(*args,**kwargs):
- start_time = time.time()
- fun()
- stop_time = time.time()
- func_time = stop_time - start_time
- print('the fun run time is %s' %func_time)
- return wapper
- @timer
- def test1():
- time.sleep(3)
- print('the fun1 is test1')
- test1()
- @timer
- def test2(name,age):
- print("test2", %(name,age))
- test2('chen','22)
来源: http://www.bubuko.com/infodetail-2635936.html