python装饰器之中级篇

41 篇文章 1 订阅
# Author Richard_Kong
# !/usr/bin/env python
# --*-- encoding:utf-8 --*--
"""
如果函数带有返回值,怎么办?
这就是更高级的装饰器:
1、带参数的装饰器:
@auth(auth_type="local")
此时它是一个函数,这种情况下 由于带有括号,会立即执行,但是只要它的返回值是一个装饰器就没问题
2、基于类的装饰器 和 带参数的类的装饰器


什么是装饰器呢:
装饰器:外部函数传入被装饰函数名,内部函数返回装饰函数名
特点:1、不修改被装饰函数的名称,2、不修改被装饰函数的源代码
home = timmer(home),等式右侧返回的是wrapper的内存地址,再将其赋值给home,这里的home不再是
原来的那个函数,而是被装饰以后的函数
像home = timmer(home)这样的写法,python给了我们特定的语法,@语法糖

如果一个函数被多个装饰器修饰。那它的执行顺序是由下到上
"""

def auth(auth_type):
    print("auth_type:::",auth_type)
    def outer_wrapper(func):
        def wrapper(*args,**kwargs):
            if auth_type=="local":
                username = input("please input username:")
                password = input("Please input password:")
                if username == "richard_kong" and password == "abs123":
                    print("login successful")
                    func()
                else:
                    exit("username or password is wrong!!")
            elif auth_type =="lapd":
                print("搞毛线lapd......不会!")
        return wrapper
    return outer_wrapper


@auth(auth_type="local")
def home(): # home = auth(home)
    print("from home !!!")


def abs():
    print("from abs!!!")

def login():
    print("from abs!!!")


home()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值