【python】基础四:装饰器

装饰器

所谓装饰器其实就是高阶函数函数嵌套结合起来的高级应用。装饰器的功能:简单来说,就是在不改变函数的调用方式的情况下为函数增加某一个特定的功能。
高阶函数:把函数当作参数传入。
函数嵌套:在函数里面用def字段定义一个函数。

例子1:

如下面的例子所示,添加一个@timer装饰器,为test1和test2函数增加一个计算函数执行时间的功能,而且不改变这两个函数的调用方式。

__author__ = '__yuanlei__'

import time
def timer(func):   # timer(test1)   func = test1 
    def deco(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)   #run test1()
        stop_time = time.time()
        print("the func run time is %s"%(stop_time-start_time))
    return deco

@timer  #test1 = timer(test1)
def test1():
    time.sleep(1)
    print("in the test1")

@timer  #test2 = timer(test2)
def test2(name, age):
    time.sleep(:)
    print("test:",name,age)

test1()
test2("yl",25)

# 输出
# in the test1
# the func run time is 1.0
# ('test2:', 'yl', 25)
# the func run time is 2.00100016594

例子2:使得装饰器可以出入函数

__author__ = '__yuanlei__'

import time
user, passwd = 'yl','1993'
def auth(auth_type):
    print("auth func:",auth_type)
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print("wrapper func args:",*args, **kwargs)
            if auth_type == "local":
                username = input("Username:").strip()
                password = input("Password:").strip()
                if user == username and passwd == password:

                    print("\033[32;1mUser has passed authentication\033[0m")
                    res = func(*args, **kwargs)
                    print("--after authentication")
                    return res
                else:
                    exit("\033[32;1mInvalid username or password\033[0m")
            elif auth_type == 'ldap':
                print('ldap,do not understand......')
        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()
#home()
print(home())
bbs()


# 输出:
# auth func: local
# auth func: ldap
# welcome to index page
# wrapper func args:
# Username:yl
# Password:1993
# User has passed authentication
# welcome to home page
# --after authentication
# from home
# wrapper func args:
# ldap,do not understand......
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuanCruise

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值