zoukankan      html  css  js  c++  java
  • python学习-装饰器

    装饰器

    #!/usr/bin/env python
    # -*- conding:utf-8 -*-
    # Author : QiuMeng
    
    auth = ["james",'123123']
    
    def login(auth_type):   #接受login的参数
        print(auth_type) #local
        def outwapper(func):#利用func将bbs这个函数接收到
            print(func) #<function bbs at 0x10b164488>
            def wapper(*args,**kwargs):   #此事wapper=bbs,
                print(*args,**kwargs) #james 123123
                if auth_type == "local":
                    # 所以wapper(sername,password)=bbs(sername,password),所以需要在wapper这里填写动态
                    # 参数用来接收原函数使用时调用的参数,以便于下面的func执行的时候调用改参数
                    user=input("input your username:")
                    passwd=input("input your password:")
                    if user == auth[0] and passwd == auth[1]:  #此处验证的信息并不是原函数传入的参数,
                        # 原函数传入的参数不能在此使用
                        print("login access!")
                        result = func(*args,**kwargs)  #func执行,接受wapper传入的参数,即为原函数bbs执行传入的参数
                        return result   #原函数如果有返回值,将func执行后的结果返回
                    else: #原函数返回值如果没走前面,既result为None,走的else,那么返回值为None,我们可以在原函数进行判断
                        print("login error! ")
                        result="error!"  # 给函数的其他结果返回值进行赋值,这样依然不会修改源函数代码
                        return result
                elif auth_type == "ldap":
                    print("ldap的方式未实现")
    
            return wapper  #返回wapper的内存地址,切记不能加括号,加括号为调用
        return outwapper
    
    
    
    def index():
        print("Welcome to index page")
    
    @login(auth_type="ldap")     #装饰器调用方式,
    # 装饰器调用如果有参数,那么在装饰器的第一层应该接收装饰器的参数,第二层接受原函数,第三层接受函数的参数
    def bbs(username,password):
        print("Welcome %s to index page" %(username))
        return "Login status"
    
    
    def home(username,password):
        print("Welcome %s to index page" %(username))
    
    
    index()
    res = bbs("james",'123123')  #原函数执行传入参数
    print(res)
    
  • 相关阅读:
    ZKW费用流修正
    BZOJ 1060 [ZJOI2007]时态同步
    BZOJ 1059 [ZJOI2007]矩阵游戏
    腾讯WEB前端开发面试经历,一面二面HR面,面面不到!
    亲历腾讯WEB前端开发三轮面试经历及面试题
    2015大型互联网公司校招都开始了,薪资你准备好了嘛?
    10款最好的 Bootstrap 3.0 免费主题和模板
    python3之urllib基础
    python3下应用requests
    python心得二(编码问题)
  • 原文地址:https://www.cnblogs.com/forsaken627/p/6518526.html
Copyright © 2011-2022 走看看