装饰器的使用

使用闭做包装饰器

def filter(func):
    def test(username,password):
        if username == 'admin' and password == '123456':
            func(username,password)
        else:
            print('登录失败')
    return test 

@filter 
def login(username,password):
    print('登录成功')

username = input('请输入用户名:')
password = input('请输入密码:')
login(username,password)


使用类做装饰器

class filter(object):
    def __init__(self,func):
        self.func = func 

    def __call__(self,username,password):
        if username == 'admin' and password == '123456':
            self.func(username,password)
        else:
            print('登录失败')

@filter
def login(username,password):
    print('登录成功')

username = input('请输入用户名:')
password = input('请输入密码:')
login(username,password)


使用多层装饰器

def filter_username(func):
    print('username')
    def test(username,password):
        if username == 'admin':
            func(username,password)
        else:
            print('用户名错误')

    return test 

def filter_password(func):
    print('password')
    def test(username,password):
        if password == '123456':
            func(username,password)
        else:
            print('密码错误')

    return test

@filter_username
@filter_password
def login(username,password):
    print('登录成功')

username = input('请输入用户名:')
password = input('请输入密码:')
login(username,password)

*装饰器先从最外层开始装饰

猜你喜欢

转载自blog.csdn.net/sdzhr/article/details/81045597