裝飾器

# 裝飾器 本質是函數,(裝飾其他函數),就是爲其他函數添加附加功能
#原則  1.不能修改被裝飾的函數的源代碼 2.不能修改被裝飾的函數的調用方式
#實現裝飾器知識 1.函數即變量 2.高階函數 3.嵌套函數   裝飾器=高階函數+嵌套函數

#裝飾器例子
import time
def timmer(func):
    def warapper(*args,**kwargs):
        start_time=time.time()
        func()
        stop_time=time.time()
        print("the func run time is %s" %(stop_time-start_time))
    return warapper


@timmer  #使用裝飾器timmer
def test1():
    time.sleep(3)   #運行3秒
    print('in the test1')

test1()
'''
#函數即變量 函數就是變量 有內存回收機制 變量名或函數名 del 內存就會回收,不del就不會回收
#函數先定義在引用
'''
def foo():
    print('in the foo')
    bar()   #函數先定義在引用 即先執行完def操作,在引用bar  或叫先聲明在調用

def bar():
    print('in the bar')

foo()
#lambda匿名函數
cal = lambda x:x*3
cal(3)
print(cal(3  ))

#def foo():
#    print('in the foo')
#    bar()   #函數先定義在引用 即先執行完def操作,在引用bar  或叫先聲明在調用
#foo()   #已經先調用了foo函數  但bar函數還沒來得及定義聲明
#def bar():
#    print('in the bar')

#高階函數 1.把一個函數名當成實參傳給另一個函數(在不修改被裝飾函數源代碼的情況下爲其添加功能)
#2.返回值中包含函數名(不修改函數的調用方式)
def bar():
    print('in the bar')

def test1(func):         #傳入bar函數名
    print(func)          #返回bar的內存地址
    func()

test1(bar)      #傳入bar函數名


import time
def bar():
    time.sleep(1)
    print('in the bar')

def test1(func):         #傳入bar函數名
    start_time=time.time()
    func()  #運行bar函數
    stop_time=time.time()
    print("the func run time is %s "%(stop_time-start_time))
test1(bar)

import time
def bar():
    time.sleep(1)
    print('in the bar')
def test2(func):
    print(func)
    return func

#print(test2(bar))
#t = test2(bar) #返回值傳給t   print把返回值輸出到屏幕上
#print(t)
#t()
bar = test2(bar) #覆蓋之前的bar 可以獲取到bar的內存地址
bar()       #可以獲取到bar的內存地址 增加的新功能

#嵌套函數
def foo():
    print('in the foo')
    def bar():                        #函數的嵌套  函數裏面在嵌套一個函數
        print('in the bar')
    bar()
foo()

#def test1():
#    test2()  #這種叫函數的調用 不叫函數嵌套
#test1()
#作用域 從裏往外
x = 0
def gran():
    x = 1
    def da():
        x = 2
        def so():
            x = 3
            print(x)
        so()
    da()
gran()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章