1. 程式人生 > >python裝飾器了解

python裝飾器了解

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

@timer

def test2(name,age):

    print("test2", %(name,age))

test2(‘chen‘,‘22)

python裝飾器了解