1. 程式人生 > >閉包,裝飾器

閉包,裝飾器

print conf 文章 tar 函數的參數 led world 方法 str

閉包

1. 函數引用

def test1():
    print("--- in test1 func----")

# 調用函數
test1()

# 引用函數
ret = test1

print(id(ret))
print(id(test1))

#通過引用調用函數
ret()

運行結果:

--- in test1 func----
140212571149040
140212571149040
--- in test1 func----

2. 什麽是閉包

# 定義一個函數
def test(number):

    # 在函數內部再定義一個函數,並且這個函數用到了外邊函數的變量,那麽將這個函數以及用到的一些變量稱之為閉包
    def test_in(number_in):
        print("in test_in 函數, number_in is %d" % number_in)
        return number+number_in
    # 其實這裏返回的就是閉包的結果
    return test_in


# 給test函數賦值,這個20就是給參數number
ret = test(20)

# 註意這裏的100其實給參數number_in
print(ret(100))

#註 意這裏的200其實給參數number_in
print(ret(200))

運行結果:


in test_in 函數, number_in is 100
120

in test_in 函數, number_in is 200
220

3. 看一個閉包的實際例子:

def line_conf(a, b):
    def line(x):
        return a*x + b
    return line

line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
print(line1(5))
print(line2(5))

這個例子中,函數line與變量a,b構成閉包。在創建閉包的時候,我們通過line_conf的參數a,b說明了這兩個變量的取值,這樣,我們就確定了函數的最終形式(y = x + 1和y = 4x + 5)。我們只需要變換參數a,b,就可以獲得不同的直線表達函數。由此,我們可以看到,閉包也具有提高代碼可復用性的作用。

如果沒有閉包,我們需要每次創建直線函數的時候同時說明a,b,x。這樣,我們就需要更多的參數傳遞,也減少了代碼的可移植性。

註意點:

由於閉包引用了外部函數的局部變量,則外部函數的局部變量沒有及時釋放,消耗內存

4. 修改外部函數中的變量

python3的方法

def counter(start=0):
    def incr():
        nonlocal start
        start += 1
        return start
    return incr

c1 = counter(5)
print(c1())
print(c1())

c2 = counter(50)
print(c2())
print(c2())

print(c1())
print(c1())

print(c2())
print(c2())

python2的方法


def counter(start=0):
    count=[start]
    def incr():
        count[0] += 1
        return count[0]
    return incr

c1 = closeure.counter(5)
print(c1())  # 6
print(c1())  # 7
c2 = closeure.counter(100)
print(c2())  # 101
print(c2())  # 102

裝飾器

裝飾器是程序開發中經常會用到的一個功能,用好了裝飾器,開發效率如虎添翼,所以這也是Python面試中必問的問題,但對於好多初次接觸這個知識的人來講,這個功能有點繞,自學時直接繞過去了,然後面試問到了就掛了,因為裝飾器是程序開發的基礎知識,這個都不會,別跟人家說你會Python, 看了下面的文章,保證你學會裝飾器。

1、先明白這段代碼

#### 第一波 ####
def foo():
    print(‘foo‘)

foo  # 表示是函數
foo()  # 表示執行foo函數

#### 第二波 ####
def foo():
    print(‘foo‘)

foo = lambda x: x + 1

foo()  # 執行lambda表達式,而不再是原來的foo函數,因為foo這個名字被重新指向了另外一個匿名函數

函數名僅僅是個變量,只不過指向了定義的函數而已,所以才能通過 函數名()調用,如果 函數名=xxx被修改了,那麽當在執行 函數名()時,調用的就不知之前的那個函數了

def w1(func):
    def inner():
        # 驗證1
        # 驗證2
        # 驗證3
        func()
    return inner

@w1
def f1():
    print(‘f1‘)

python解釋器就會從上到下解釋代碼,步驟如下:

  1. def w1(func): ==>將w1函數加載到內存
  2. @w1

沒錯, 從表面上看解釋器僅僅會解釋這兩句代碼,因為函數在 沒有被調用之前其內部代碼不會被執行。

從表面上看解釋器著實會執行這兩句,但是 @w1 這一句代碼裏卻有大文章, @函數名 是python的一種語法糖。

上例@w1內部會執行一下操作:

執行w1函數

執行w1函數 ,並將 @w1 下面的函數作為w1函數的參數,即:@w1 等價於 w1(f1) 所以,內部就會去執行:

def inner(): 
    #驗證 1
    #驗證 2
    #驗證 3
    f1()    # func是參數,此時 func 等於 f1 
return inner# 返回的 inner,inner代表的是函數,非執行函數 ,其實就是將原來的 f1 函數塞進另外一個函數中

w1的返回值

將執行完的w1函數返回值 賦值 給@w1下面的函數的函數名f1 即將w1的返回值再重新賦值給 f1,即:

新f1 = def inner(): 
            #驗證 1
            #驗證 2
            #驗證 3
            原來f1()
        return inner

所以,以後業務部門想要執行 f1 函數時,就會執行 新f1 函數,在新f1 函數內部先執行驗證,再執行原來的f1函數,然後將原來f1 函數的返回值返回給了業務調用者。

如此一來, 即執行了驗證的功能,又執行了原來f1函數的內容,並將原f1函數返回值 返回給業務調用著

Low BBB 你明白了嗎?要是沒明白的話,我晚上去你家幫你解決吧!!!

3. 再議裝飾器


# 定義函數:完成包裹數據
def makeBold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

# 定義函數:完成包裹數據
def makeItalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makeBold
def test1():
    return "hello world-1"

@makeItalic
def test2():
    return "hello world-2"

@makeBold
@makeItalic
def test3():
    return "hello world-3"

print(test1())
print(test2())
print(test3())

運行結果:

<b>hello world-1</b>
<i>hello world-2</i>
<b><i>hello world-3</i></b>

4. 裝飾器(decorator)功能

  1. 引入日誌
  2. 函數執行時間統計
  3. 執行函數前預備處理
  4. 執行函數後清理功能
  5. 權限校驗等場景
  6. 緩存

5. 裝飾器示例

例1:無參數的函數


from time import ctime, sleep

def timefun(func):
    def wrapped_func():
        print("%s called at %s" % (func.__name__, ctime()))
        func()
    return wrapped_func

@timefun
def foo():
    print("I am foo")

foo()
sleep(2)
foo()

上面代碼理解裝飾器執行行為可理解成

foo = timefun(foo)
# foo先作為參數賦值給func後,foo接收指向timefun返回的wrapped_func
foo()
# 調用foo(),即等價調用wrapped_func()
# 內部函數wrapped_func被引用,所以外部函數的func變量(自由變量)並沒有釋放
# func裏保存的是原foo函數對象

例2:被裝飾的函數有參數

from time import ctime, sleep

def timefun(func):
    def wrapped_func(a, b):
        print("%s called at %s" % (func.__name__, ctime()))
        print(a, b)
        func(a, b)
    return wrapped_func

@timefun
def foo(a, b):
    print(a+b)

foo(3,5)
sleep(2)
foo(2,4)

例3:被裝飾的函數有不定長參數

from time import ctime, sleep

def timefun(func):
    def wrapped_func(*args, **kwargs):
        print("%s called at %s"%(func.__name__, ctime()))
        func(*args, **kwargs)
    return wrapped_func

@timefun
def foo(a, b, c):
    print(a+b+c)

foo(3,5,7)
sleep(2)
foo(2,4,9)

例4:裝飾器中的return

from time import ctime, sleep

def timefun(func):
    def wrapped_func():
        print("%s called at %s" % (func.__name__, ctime()))
        func()
    return wrapped_func

@timefun
def foo():
    print("I am foo")

@timefun
def getInfo():
    return ‘----hahah---‘

foo()
sleep(2)
foo()


print(getInfo())

執行結果:

foo called at Fri Nov  4 21:55:35 2016
I am foo
foo called at Fri Nov  4 21:55:37 2016
I am foo
getInfo called at Fri Nov  4 21:55:37 2016
None

如果修改裝飾器為return func(),則運行結果:

foo called at Fri Nov  4 21:55:57 2016
I am foo
foo called at Fri Nov  4 21:55:59 2016
I am foo
getInfo called at Fri Nov  4 21:55:59 2016
----hahah---

總結:

  • 一般情況下為了讓裝飾器更通用,可以有return

例5:裝飾器帶參數,在原有裝飾器的基礎上,設置外部變量

#decorator2.py

from time import ctime, sleep

def timefun_arg(pre="hello"):
    def timefun(func):
        def wrapped_func():
            print("%s called at %s %s" % (func.__name__, ctime(), pre))
            return func()
        return wrapped_func
    return timefun

# 下面的裝飾過程
# 1. 調用timefun_arg("itcast")
# 2. 將步驟1得到的返回值,即time_fun返回, 然後time_fun(foo)
# 3. 將time_fun(foo)的結果返回,即wrapped_func
# 4. 讓foo = wrapped_fun,即foo現在指向wrapped_func
@timefun_arg("itcast")
def foo():
    print("I am foo")

@timefun_arg("python")
def too():
    print("I am too")

foo()
sleep(2)
foo()

too()
sleep(2)
too()

可以理解為

foo()==timefun_arg("itcast")(foo)()

例6:類裝飾器(擴展,非重點)

裝飾器函數其實是這樣一個接口約束,它必須接受一個callable對象作為參數,然後返回一個callable對象。在Python中一般callable對象都是函數,但也有例外。只要某個對象重寫了 __call__() 方法,那麽這個對象就是callable的。

class Test():
    def __call__(self):
        print(‘call me!‘)

t = Test()
t()  # call me

類裝飾器demo


class Test(object):
    def __init__(self, func):
        print("---初始化---")
        print("func name is %s"%func.__name__)
        self.__func = func
    def __call__(self):
        print("---裝飾器中的功能---")
        self.__func()
#說明:
#1. 當用Test來裝作裝飾器對test函數進行裝飾的時候,首先會創建Test的實例對象
#   並且會把test這個函數名當做參數傳遞到__init__方法中
#   即在__init__方法中的屬性__func指向了test指向的函數
#
#2. test指向了用Test創建出來的實例對象
#
#3. 當在使用test()進行調用時,就相當於讓這個對象(),因此會調用這個對象的__call__方法
#
#4. 為了能夠在__call__方法中調用原來test指向的函數體,所以在__init__方法中就需要一個實例屬性來保存這個函數體的引用
#   所以才有了self.__func = func這句代碼,從而在調用__call__方法中能夠調用到test之前的函數體
@Test
def test():
    print("----test---")
test()
showpy()#如果把這句話註釋,重新運行程序,依然會看到"--初始化--"

運行結果如下:

---初始化---
func name is test
---裝飾器中的功能---
----test---

閉包,裝飾器