8.9 装饰器 嵌套解释

装饰器

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

在嵌套函数timer()内定义一个高阶函数deco()

用高阶函数deco()装饰函数test1()

同时返回高阶函数名——函数内存地址deco

然后test1=deco 

#把deco内存地址传给test1变量

此时执行test1()就是执行deco()即 test1()=deco()

如果原来的test1()有参数,

则高阶函数也应该接收参数test1(a)=deco(a)

新test1()比旧test1()功能更全,

 

#无参数传递函数的装饰举例

import time

 

 

def timer(func):    #装饰器函数---嵌套函数

    def deco():    #定义实际装饰函数----高阶函数

        #print(func)

        start_time=time.time()

        func()                       #被装饰函数

        stop_time=time.time()

        print("程序运行时间为:%s" %(start_time-stop_time))

    return deco                 #返回高阶函数的内存地址(函数名字)

@timer                       #装饰器的使用

def test1():

    time.sleep(3)

    print("in test1")

# def test2():

#     time.sleep(4)

#     print("in test2")

test1()             #本质是deco()

#有参数传递装饰器

import time

 

 

def timer(func):

    def deco(*args,**kwargs):

        #print(func)

        start_time=time.time()

        func(*args,**kwargs)

        stop_time=time.time()

        print("程序运行时间为:%s" %(start_time-stop_time))

    return deco

@timer

def test1():

    time.sleep(3)

    print("in test1")

 

@timer

def test2(name):

    time.sleep(1)

    print(name)

test1()

test2("wanghui")

    1. 装饰器的高级用法

import time

user,passwd = 'alex','abc123'

def auth(auth_type):

    print("auth func:",auth_type)

    def outer_wrapper(func):

        def wrapper(*args, **kwargs):

            print("wrapper func args:", *args, **kwargs)

            if auth_type == "local":

                username = input("Username:").strip()

                password = input("Password:").strip()

                if user == username and passwd == password:

                    print("\033[32;1mUser has passed authentication\033[0m")

                    res = func(*args, **kwargs)  # from home

                    print("---after authenticaion ")

                    return res

                else:

                    exit("\033[31;1mInvalid username or password\033[0m")

            elif auth_type == "ldap":

                print("搞毛线ldap,不会。。。。")

 

        return wrapper

    return outer_wrapper

 

def index():

    print("welcome to index page")

@auth(auth_type="local") # home = wrapper()

def home():

    print("welcome to home  page")

    return "from home"

 

@auth(auth_type="ldap")

def bbs():

    print("welcome to bbs  page")

 

index()

print(home()) #wrapper()

bbs()

 

三层意思

第一层,装饰器添加验证功能

第二层,装饰器添加返回功能

第三层,根据装饰器函数的关键字参数,选择验证方式

        验证方式可以在装饰器的高阶函数里面实现

        但关键字参数传递给装饰器需要再加一层嵌套函数接收-关键字参数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值