190401装饰器-高阶函数-闭包

Posted l-dongf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了190401装饰器-高阶函数-闭包相关的知识,希望对你有一定的参考价值。

一、装饰器

  1. 装饰器本质是函数
  2. 为其他函数添加附加功能
  3. 不修改被修饰函数的源代码
  4. 不修改被修饰函数的调用方式
  • 装饰器示例
import time

def timmer(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        res = func(*args,**kwargs)
        stop_time = time.time()
        print("函数的运行时间:%s" % (stop_time - start_time))
        return res
    return wrapper

@timmer
def calc(l):

    s = 0
    for i in l:
        s += i
        time.sleep(0.1)
    return s

print(calc(range(20)))
  • 装饰器示例2
import time

def timmer(func):
    def wrapper():
        start_time = time.time()
        func()  #运行传进来的f函数
        stop_time = time.time()
        print("函数的运行时间是: %s" % (stop_time - start_time))
    return wrapper

@timmer  #f = timmer(f)  #将f函数传给timmer
def f():
    time.sleep(3)
    print("f 函数运行完成。")

f()  #执行wrapper()
  • 修饰带返回值的函数
import time

def timmer(func):
    def wrapper():
        start_time = time.time()
        res = func()  #运行传进来的f函数
        stop_time = time.time()
        print("函数的运行时间是: %s" % (stop_time - start_time))
        return res  #将f函数的返回值返回
    return wrapper

@timmer  #f = timmer(f)  #将f函数传给timmer
def f():
    time.sleep(3)
    print("f 函数运行完成。")
    return "f函数的返回值"
  • 修饰带参数的函数
import time

def timmer(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        res = func(*args,**kwargs)  #运行传进来的f函数
        stop_time = time.time()
        print("函数的运行时间是: %s" % (stop_time - start_time))
        return res  #将f函数的返回值返回
    return wrapper

@timmer  #f = timmer(f)  #将f函数传给timmer
def f(name):
    time.sleep(1)
    print("f 函数运行完成。函数的参数是:%s" %name)
    return "f函数的返回值"

res = f("dongfei")  #执行wrapper()
print(res)
  • 认证登录装饰器示例
def auth(func):
    def warpper(*args,**kwargs):
        username = input("your username: ")
        password = input("your password: ")
        if username == "dongfei" and password == "123":
            res = func(*args,**kwargs)
            return res
        else:
            print("username or password error!")
    return warpper


def index():
    print("welcome to my index page.")

@auth
def home(name):
    print("%s go home" %name)

@auth
def shopping_car():
    print("your shopping_car")

index()
home("dongfei")
shopping_car()
  • 模拟记录session
user_list = [
    {"username":"dongfei", "password":"123456"},
    {"username":"dongfei2", "password":"123456"},
    {"username":"dongfei3", "password":"123456"},
    {"username":"dongfei4", "password":"123456"},
]

current_dic = {"username":None, "login_status":False}

def auth(func):
    def warpper(*args,**kwargs):
        if current_dic["username"] and current_dic["login_status"]:
            res = func(*args, **kwargs)
            return res
        username = input("your username: ")
        password = input("your password: ")
        for user_dic in user_list:
            if username == user_dic["username"] and password == user_dic["password"]:
                current_dic["username"] = username
                current_dic["login_status"] = True
                res = func(*args,**kwargs)
                return res
        else:
            print("username or password error!")
    return warpper


def index():
    print("welcome to my index page.")

@auth
def home(name):
    print("%s go home" %name)

@auth
def shopping_car():
    print("your shopping_car")

index()
home("dongfei")
shopping_car()
  • 带参数的装饰器
user_list = [
    {"username":"dongfei", "password":"123456"},
    {"username":"dongfei2", "password":"123456"},
    {"username":"dongfei3", "password":"123456"},
    {"username":"dongfei4", "password":"123456"},
]

current_dic = {"username":None, "login_status":False}

def auth(auth_type):
    def auth_func(func):
        def warpper(*args,**kwargs):
            if auth_type == "file_db":
                if current_dic["username"] and current_dic["login_status"]:
                    res = func(*args, **kwargs)
                    return res
                username = input("your username: ")
                password = input("your password: ")
                for user_dic in user_list:
                    if username == user_dic["username"] and password == user_dic["password"]:
                        current_dic["username"] = username
                        current_dic["login_status"] = True
                        res = func(*args,**kwargs)
                        return res
                else:
                    print("username or password error!")
            elif auth_type == "mysql_db":
                print("请使用%s认证:" %auth_type)
            else:
                print("无效的认证类型")
        return warpper
    return auth_func

@auth("ldap")
def index():
    print("welcome to my index page.")

@auth(auth_type="mysql_db")  # @auth(auth_type="mysql") 等于 @auth_func
def home(name):
    print("%s go home" %name)

@auth(auth_type="file_db")
def shopping_car():
    print("your shopping_car")

index()
home("dongfei")
shopping_car()

二、高阶函数

  1. 函数接受的参数是一个函数名
  2. 函数的返回值是一个函数名
  3. 满足以上条件的任意一个都是高阶函数
import time

def foo():
    print("from foo")
    time.sleep(2)

def timmer(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print("函数的运行时间:%s" % (stop_time - start_time))
    return func

foo = timmer(foo)
foo()

三、解压序列

>>> a,*_,c = [1,2,3,4,5,6,7,8]  #取第一个和最后一个值
>>> a
1
>>> c
8
>>> _
[2, 3, 4, 5, 6, 7]

以上是关于190401装饰器-高阶函数-闭包的主要内容,如果未能解决你的问题,请参考以下文章

装饰器,闭包,高阶函数,嵌套函数

Go的魅力, 函数式(柯里化, 闭包, 高阶函数), Python@装饰器, 封装

Python基础高阶函数+函数嵌套+闭包 ==装饰器

Python-20_装饰器-01_基础高阶函数闭包

Python--高阶函数函数嵌套名称空间及变量作用域闭包装饰器

Python函数作用域嵌套函数闭包函数高阶函数及装饰器的理解