首页 > 编程语言 > 详细

课堂练习-python 装饰器

时间:2017-09-21 10:48:16      阅读:218      评论:0      收藏:0      [点我收藏+]
#无传参版
import time
def timer(func):# 函数test当做了一个变量传给了func
    def conut():
        start_time=time.time()
        func()
        stop_time=time.time()
        print(the func run time is %s%(stop_time-start_time))
    return conut

# @timer  # 相当于test=timer(test)
def test():
    time.sleep(3)
    print(in the test)

test=timer(test)
test()

#有传参版
import time
def timer(func):# 函数test当做了一个变量传给了func
    def conut(*args,**kwargs):
        start_time=time.time()
        func(*args,**kwargs)
        stop_time=time.time()
        print(the func run time is %s%(stop_time-start_time))
    return conut

@timer  # 相当于test=timer(test)
def test(name,age):
    time.sleep(3)
    print(%s is %s%(name,age))

# test=timer(test)
test(bruce,22)

#高级版

import time
name,password=bruce,123456

def auth(auth_type):
    def out_wrapper(func):
        def wrapper(*args,**kwargs):
            if auth_type == local:
                username=input(User:).strip()
                passwd=input(Passwd:).strip()
                if username == name and passwd == password:
                    print(\033[32;1m认证成功!\033[32;0m)
                    ret = func(*args,**kwargs)
                    return ret
                else:
                    exit()
            elif auth_type == ldap:
                print(不会!)
        return wrapper
    return out_wrapper

@auth(auth_type=ldap)
def index():
    print(welcom to index page)

@auth(auth_type=local)
def home():
    print(welcom to home page)
    return home

index()
home()

 

课堂练习-python 装饰器

原文:http://www.cnblogs.com/bruce61/p/7567237.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!