装饰器与函数多层嵌套
# coding: utf-8
def login(func):
print("the first level")
def inner1(*args,**kwargs):
print("the second level")
def inner2(*args):
print("the third level")
func(*args)
func(*args)
return inner2
return inner1
# @login相当于 tv = login(tv) ,把 tv 函数的内存地址传给login的参数 func ,login函数返回其内部函数 inner1 的内存地址 给tv 。
#当执行tv函数 的时候,其实是执行了login的 inner1 函数。 即 login 原来的参数 func 指向 tv ; tv 指向 inner1 。
@login
def tv(name,password):
print("Welcome [%s] [%s] to TV page" % (name,password) )
@login
def movie(name):
print("Welcome [%s] to movie page" % name)
@login
def picture(name,password,type):
print("Welcome [%s] [%s] to picture type [%s]" %(name,password,type))
print(tv)
tv = tv("zhou","123")
print(tv)
tv = tv("zhouding","123456")
print(tv)
movie("Durant")
picture("kobe bryant","kobe123","nature")
输出结果:
the first level
the first level
the first level
<function login.<locals>.inner1 at 0x02F34150>
the second level
Welcome [zhou] [123] to TV page
<function login.<locals>.inner1.<locals>.inner2 at 0x02F34300>
the third level
Welcome [zhouding] [123456] to TV page
None
the second level
Welcome [Durant] to movie page
the second level
Welcome [kobe bryant] [kobe123] to picture type [nature]
注:函数的*args 参数可以接收一个或者多个参数。
浙公网安备 33010602011771号