20180420 装饰器3

Index

Home

Bbs

登陆验证

装饰器需要验证登陆账户和密码

根据不同的验证方式,

装饰器有参数实现,不同的验证方式,

两次嵌套函数,来实现验证

最内层可引入变量来接受 函数的返回值,再一次return 变量,实现被装饰函数内部的返回值


import time

user = "li"
password = "li"
def atuo(auth_type):
    def outwrapper(func):
        def wrapper(*args, **kwargs):
            if auth_type == 'local':
                username = input("please input your name")
                passname = input("please input your password")
                if user == username and password == passname:
                    res = func(*args, **kwargs)
                    return res
                else:
                    print("用户名和密码不正确")
                    exit()
            elif auth_type == 'ldpe':
                exit("不会,不会,不会!")


        return wrapper
    return outwrapper


def index():
    print("welcome to  the  index  ")
@atuo("local")
def home():
    print("welcome to the home")
    return "from home "


@atuo("ldpe")
def bbs():
    print("welcome to the bbs")

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

疑问:如果装饰器的参数没有添加变量,比如@atuo(),该怎么处理,让它不报错?

猜你喜欢

转载自blog.csdn.net/weixin_42020378/article/details/80025223