码迷,mamicode.com
首页 > 编程语言 > 详细

课堂练习-python 装饰器

时间:2017-09-21 11:27:15      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:index   logs   nbsp   import   stop   练习   test   func   top   

#无传参版
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 装饰器

标签:index   logs   nbsp   import   stop   练习   test   func   top   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!