python装饰器了解

装饰器作为python的中的一个功能可以说是非常重要的,也是学习python中的一个门坎,可能很多人会觉得在学习装饰器的时候很容易会搞迷糊,最在看python核心编程时和python之阐时感觉有点明白了,在此抛砖引玉。

装饰器的作用最大的特点的是,在不修改原代码的情况下,给原有的代码附加功能,所以要写装饰器要遵守二个规则:

  1. 不能修改被装饰的函数
  2. 不能修改函数的调用方式

想要搞明白装饰器需要的知识点

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()

猜你喜欢

转载自blog.51cto.com/12741079/2126252