博客园 首页 私信博主 显示目录 隐藏目录 管理 动画

python 装饰器的基本应用

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: liang 
import time


#用户名密码
user,passwd='liang','123456'


#建立一个装饰器 wap_type 对应是home的@wap(wap_type="local")
def wap(wap_type):

    def outer_wrapper(func):  # func这个函数传值 等于 吧home传过来当做形参
        def doce(*args, **kwargs):  # doce函数相当于 *args **kwarge 不管传递什么都可以接受进来

            if wap_type=="local":     #判断 wap_type= local

                start_time=time.time()    #开始记录时间

                username = input("Username:").strip()    #用户输入
                password = input("Password:").strip()     #密码

                if username == user and password == passwd:  #判断用户输入的用户密码
                    print("welcome to home is ")
                    res2 = func(*args, **kwargs)            #res2 表示 func() 的返回值
                    print("------------返回值-------------")
                    stop_time=time.time()                    #结束时间
                    print("程序用时时间为%s"%(stop_time-start_time))     ## 输出结束时间
                    return res2                           ## 把 返回值放入到返回值中.

                else:
                    exit("Invlin is username password")       #密码错误就直接退出

            elif wap_type=="ldap":
                start_time = time.time()
                username = input("Username:").strip()
                password = input("Password:").strip()

                if username == user and password == passwd:
                    print("welcome to bbs is ")
                    res3 = func(*args, **kwargs)
                    print("------------返回值-------------")
                    stop_time = time.time()
                    print("程序用时时间为%s" % (stop_time - start_time))
                    return res3
                else:
                    exit("Invlin is username password")


        return doce              # 返回doce
    return outer_wrapper       #返回outer_wrapper

@wap(wap_type="local")
def home():
    print("welcome to  home")
    return "from yes"

@wap(wap_type="ldap")
def bbs():
    print("in the bbs")
    return "1245654"


tes2=home()
print(tes2)
tes3=bbs()
print(tes3)

 

posted @ 2017-11-19 17:24  crazy_py  阅读(178)  评论(0编辑  收藏  举报