Python---装饰器

装饰器:其本身为函数,用来装饰其他函数,也就是为其他函数增加功能。

装饰器设计遵循原则:1.不能修改被装饰函数的源代码

                                2.不能修改被装饰函数的调用方式

通常一个装饰器是由 高阶函数和嵌套函数组成。且会把函数当成变量使用。

装饰器1:被装饰函数有无参数通用版,装饰器本身无参数

import time
def timer(func):
    def deco(*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 deco

@timer   #相当于test1=timer(test1)  则test1=deco
def test1():
    time.sleep(1)
    print('in the test1')
@timer
def test2(name,age):
    print("test2:",name,age)
test1()
test2("hy",16)

装饰器2:装饰器本身带参数

import time
user,passwd="hy","123abc"

def auth (auth_type):
    print("auth_type:",auth_type)
    def deco(func):
        def wrapper(*args,**kwargs):
            username=input("Username:")
            password=input("Password:")
            if auth_type=="local":
                if username==user and password==passwd:
                    print("\033[32;1m user has passed authentication\033[0m")
                    res=func(*args,**kwargs)
                    return res
                else:
                    print("\033[31;1m Invalid username and password\033[0m")
            elif auth_type=="ldap":

                print("hehe")
        return wrapper
    return deco
def index():
    print("Welcome to index paper")
@auth(auth_type="local")
def home():
    print("Welcome to home paper")
    return
@auth(auth_type="ldap")
def bbs():
    print("Welcome to bbs paper")

index()
print(home())
bbs()

要明白其中功能用断点调试看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值