python之路5

本节内容:
装饰器

装饰器:其实本质就是一个函数
定义:为其它函数增加一个附加的功能
原则:
1、不能修改被装饰函数的源代码
2、不可以修改被装饰函数的调用方式

# 把一个函数当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加新功能)
现在就来写一个最最简单的装饰器把
def timmer(func):
	def warpper(*args,**kwargs):
		start_time = time.time()
		func()
		stop_time = time.time()
		print('the func run time is %s'%(stop_time - start_time))
	return warpper()

@timmer
def test1():
	time.sleep(3)
	print('in the test1')
test1()
这样的话,我明明只是调用了test1这个函数,但是函数却有了打印运行时间的功能。

运行test1函数,然后程序找到@timmer后 将test1传给了timmer,然后继续向下运行,在记录了开始时间后,遇到了func(),运行test1函数。
这就是一个比较完整的装饰器
import time
def timer(func):
'''record time'''
    def deco():
        stat_time = time.time()
        func()
        stop_time = time.time()
        print("the func run time is %s" %(stop_time-stat_time))
    return deco

@timer     #@timer=timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')

test1()

下面我们就让装饰器变得通用一点。

比之前的高级一点了,可以接受参数了
import time
def timer(func):
    def deco(*args,**kwargs):
        stat_time = time.time()
        func(*args,**kwargs)       #这就变成test1了,在语法糖中把 test1 当成参数传到 timer 中去了
        stop_time = time.time()
        print("the func run time is %s" %(stop_time-stat_time))
    return deco

@timer     #@timer=:test1=timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')
@timer
def test2(name):
    time.sleep(3)
    print("test2:",name)

test1()
test2('alex')


终极版

import time

user = 'alex'
passwd = 'abc123'

def auth(auth_type):
'''checkpoint function....'''
    print("auth func",auth_type)
    def outer_wrapper(func):
        def wrapper(*args,**kwargs):
            print("wrepper func args:",*args,**kwargs)
            username = input("Username").strip()
            password = input("Password").strip()

            if user == username and passwd == password:
                print("hello")
                # func(*args,**kwargs)
                return func(*args,**kwargs)     #如果像上一行那样用,那么被语法糖装饰的函数会没有 return 值
            else:
                exit("passwor or username error")
        return wrapper
    return outer_wrapper


def index():
    print("welcome to index page")

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

@auth(auth_type='ldap')
def bbs():
    print("welcome to bbs page")

index()
print(home())
bbs()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值