姜小白的Python日记Day10 装饰器

装饰器

装饰器是一种函数,用来装饰其他函数
原则:不能修改被装饰函数的源代码
不能修改被装饰函数的调用方式
装饰器对被装饰函数完全透明

实现装饰器
1.函数即“变量”(把函数当做一个变量处理)
2.高阶函数
在函数中声明另一个函数叫高阶函数
a.把函数名当做实参传入另一个函数
b.返回值中包含函数名
3.嵌套函数
高阶函数+嵌套函数=>装饰器
‘’’
import time
def timer(func):#timer(test1) func=test1
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print(“the function run time is %s” %(stop_time-start_time))
return deco

@timer#test1 = timer(test1)
def test1():
time.sleep(2)
print(“this is test1”)
@timer#test2=timer(test2)=deco test2()==deco()
def test2(name):
time.sleep(4)
print(“this is test2”,name)

test1()
test2(name)
‘’’

name = “jiang”
password = “123”

def auth(auth_type):
print(“auth func”,auth_type)
def out_wapper(func):
def wrapper(*args,**kwargs):
print(“wrapper func args”,*args,**kwargs)
user_name = input(“请输入用户名:”).strip()
user_password = input(“请输入密码:”).strip()

        if auth_type == "local":
            if user_name == name and user_password == password:
                res = func(*args,**kwargs)
                print("登陆成功")
                return res
            else:
                exit("输入错误")
        elif auth_type == "ldap":
            print("搞什么ldap")
    return wrapper
return out_wapper

def index():
print(“welcome to index page”)
@auth(auth_type = “local”)#home = wrapper
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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值