码迷,mamicode.com
首页 > 编程语言 > 详细

Python之装饰器

时间:2017-05-11 14:37:44      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:python   高阶函数   装饰器   

Python 高阶函数:

    1.把一个函数名作为实参传递给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

    2.返回值中包含函数名(不修改函数的调用方式)

def test1():
    print("in the test1")

def test2(func): #接收函数名
    func()
    print("in the test2")
    return func  #返回函数内存地址

def test3():
    str = test2(test1)  #函数名test1 作为实参传递给函数 test2,并接收test1的 内存地址赋值给str
    print(str)
    print("in the test3")
    
test3()


Python 嵌套函数:

    在函数当中再定义函数。

def test1():
    pirnt("in the test1")
    def test2(): 
        print("in the test2")


高阶函数 +  嵌套函数 => 装饰器

    装饰器,在不修改源代码的基础上新增功能,并在不改变调用方式的前提下,实现功能添加,代码实现如下:

import time
def timer(func):
    def deco(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        stop_time = time.time()
        print("the func run time %s"% (stop_time-start_time))
    return deco

@timer #test1 = timer(test1)
def test1():
    time.sleep(1)
    print("in the test1")

@timer
def test2(name):
    time.sleep(1)
    print("name: ", name)

#test1 = timer(test1) #获取的deco的内存地址,所以执行test1(),实际上就是执行deco()
test1()  #deco()

# @timer 分解步骤如下
test2 = timer(test2) # 把deco的内存地址给了test2,所以执行test2(),实际上就是执行deco()
print("test2: ", test2)
test2("lilei")  #deco("lilie")
import time

username = "alex"
password = "abc123"
def auth(mode):
    def out_wrapper(func):
        def wrapper(*args, **kwargs):
            if mode == "local":
                start_time = time.time()
                rec =func(*args, **kwargs)
                stop_time = time.time()
                print("the func run time is %s"% (stop_time-start_time))
                return rec
            elif mode == "ldap":
                print("in the ldap")
                start_time = time.time()
                rec = func(*args, **kwargs)
                stop_time = time.time()
                print("the func run time is %s" % (stop_time - start_time))
                return rec
        return wrapper
    return out_wrapper


def index():
    print("Welcome in the index page")

@auth(mode="local") #  home=wrapper()
def home(name):
    print("in the home", name)
    return "from home"

#@auth(mode="ldap")
def bbs():
    print("in the bbs")

index()
home("alex")

# @auth(mode="ldap") 分解步骤如下
#out_wrapper = auth(mode="ldap")  # 把 out_wrapper 内存地址给了 out_wrapper
# print("aa:", out_wrapper)
#bbs = out_wrapper(bbs)  # 把 wapper 的内存地址给了bbs,所以执行bbs(),实际上就是执行wapper(),
bbs = auth(mode="ldap")(bbs)  #两步整合的结果: bbs = auth(mode="ldap")(bbs)
print("bbs:", bbs)
bbs()


本文出自 “学海无涯” 博客,请务必保留此出处http://tofgetu.blog.51cto.com/12856240/1924377

Python之装饰器

标签:python   高阶函数   装饰器   

原文地址:http://tofgetu.blog.51cto.com/12856240/1924377

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!