接下来修改一下上一篇的login,将用户名传递给验证函数。
def login(func): #接收一个函数作为参数
def inner(name):
print("用户验证通过。。。。")
return func(name) #将函数返回
return inner #返回inner函数
@login
def video(name):
print("welcome %s to video!" % name)
这样当用户 张三 执行video(“张三”)时,程序怎么运行的呢?
首先会将inner返回给video. 然后video(“张三”)实际上就是执行inner(“张三”)。
也可以将用户名密码同时传进去。
def login(func):
def inner(username, password):
if username == "zhangsan" and password == '1234':
func(username, password)
else:
print("username or password is incorrect")
return inner @login
def tv(username, password):
print("Welcom %s, your password is %s" % (username, password)) tv('zhangsan', "1234")