zoukankan      html  css  js  c++  java
  • 装饰器2

    嵌套函数:

    在一个函数里面在定义一个函数(有局部变量的特性,不能在外部调用)

    针对装饰器的三个原则:

    1.函数即“变量”

    2.高阶函数

    3.嵌套函数

    举下面一个例子

    它的运行过程呢可以将装饰器阐述清楚:(每一行后都有标记#后的数字表示编号)

    a.定义auth这个函数,然后向下找定义的index()函数,发现没有参数传进去,再接着向下找,@auth(auth_type="local")函数,它将local参数传进去。

    b.接着打印传进去的参数类型#3,然后接着定义嵌套函数#4

    ,直接返回结果,此时将调用他的函数传了进来,比如传了home进来。再进入到嵌套函数wrapper里面,返回函数名,并且加了括号,相当于home()调用

    c.接着就向下走,因为home()函数是local类型,所以会让输入账户和密码

    d.“ldap”类型也是同理

    user,passwd='alex','abc123'#1
    def auth(auth_type):#2

        print("auth ",auth_type)#3

        def outer_wrapper(func):#4
            def wrapper(*args,**kwargs):#5
                print("wrapper args",*args,**kwargs)#6
                if auth_type=="local":#7
                    username=input("username:").strip()#8
                    password=input("passsword:").strip()#9
                    if user==username and passwd==password:#
                        print("33[31;1myou have logged# in33[0m")
                        return func(*args,**kwargs)#12
                    else:
                        exit("33[32;1minvalied logged33[0m")#13
                elif auth_type=="ldap":#14
                    print("不会")#15
            return wrapper#16
        return outer_wrapper#17

    def index():
        print('welcome to index ')
    @auth(auth_type="local")
    def home():
        print('welcome to home')
        return "from home"
    @auth(auth_type="ldap")

    def bbs():
        print('welcome to bbs')



    index()
    home()
    bbs()

     

  • 相关阅读:
    实现新layer的时候易犯的错误
    caffe实现focal loss层的一些理解和对实现一个layer层易犯错的地方的总结
    面经准备
    发送广播
    labelme也可以标注polygan
    中期答辩准备的东西
    授人以鱼,不如授人以渔
    python中strip()函数的理解
    栈的应用
    checkStyle使用具体解释
  • 原文地址:https://www.cnblogs.com/pythonbz/p/6284001.html
Copyright © 2011-2022 走看看