版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/plychoz/article/details/86544832
#1、编写装饰器,为函数加上认证的功能
def decorator(func):
def inner(*args, **kwargs):
name = input('用户名:').strip()
password = input('密码:')
if name == 'Noiccy' and password == '111111':
print('认证通过!')
func()
else:
print('认证失败!')
return inner
@decorator
def show():
print('Welcome to Python!')
show()
#2、编写装饰器,在每次执行被装饰函数之前让用户输入用户名,密码,给用户三次机会,登录成功之后,才能访问该函数.
def decorator(func):
def inner(*args, **kwargs):
num = 3
while num:
name = input('用户名:').strip()
password = input('密码:')
if name == 'Noiccy' and password == '111111':
print('登录成功!')
func()
break
else:
if num != 1:
print('用户名或密码错误,请重新输入(还有{}次机会)!'.format(num-1))
num -= 1
if num == 0:
print('登录失败!')
return inner
@decorator
def show():
print('Welcome to Python!')
show()
#3、随便写一个单层装饰器和多层装饰器,并将程序的执行过程用文字写下来
def decorator(func):
def inner(*args, **kwargs):
print('----')
func(*args, **kwargs)
return inner
@decorator
def show():
print('哈哈')
show()
# @decorator等价于show = decorator(show),将show函数传入decorator函数,返回inner函数,并将inner函数赋值给参数show,show = inner,
# 然后调用show函数,其实是调用decorator函数中的inner函数,执行print('----'), 然后调用func函数,即原来声明的show函数
def decorator2(char):
def decorator1(func):
def inner(*args, **kwargs):
print(char*4)
func(*args, **kwargs)
return inner
return decorator1
@decorator2('*')
def show1():
print('哈哈')
show1()
#4、函数练习,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。