- #funA 作为装饰器函数
- def funA(fn):
- #...
- fn() # 执行传入的fn参数
- #...
- return '...'
- @funA
- def funB():
- #...
- def funA(fn):
- #...
- fn() # 执行传入的fn参数
- #...
- return '...'
- def funB():
- #...
- funB = funA(funB)
- #funA 作为装饰器函数
- def funA(fn):
- print("C语言中文网")
- fn() # 执行传入的fn参数
- print("http://c.biancheng.net")
- return "装饰器函数的返回值"
- @funA
- def funB():
- print("学习 Python")
C语言中文网
学习 Python
http://c.biancheng.net
- print(funB)
装饰器函数的返回值
显然,被“@函数”修饰的函数不再是原来的函数,而是被替换成一个新的东西(取决于装饰器的返回值),即如果装饰器函数的返回值为普通变量,那么被修饰的函数名就变成了变量名;同样,如果装饰器返回的是一个函数的名称,那么被修饰的函数名依然表示一个函数。实际上,所谓函数装饰器,就是通过装饰器函数,在不修改原函数的前提下,来对函数的功能进行合理的扩充。
- def funA(fn):
- # 定义一个嵌套函数
- def say(arc):
- print("Python教程:",arc)
- return say
- @funA
- def funB(arc):
- print("funB():", a)
- funB("http://c.biancheng.net/python")
Python教程: http://c.biancheng.net/python
- def funA(fn):
- # 定义一个嵌套函数
- def say(arc):
- print("Python教程:",arc)
- return say
- def funB(arc):
- print("funB():", a)
- funB = funA(funB)
- funB("http://c.biancheng.net/python")
- def funA(fn):
- # 定义一个嵌套函数
- def say(*args,**kwargs):
- fn(*args,**kwargs)
- return say
- @funA
- def funB(arc):
- print("C语言中文网:",arc)
- @funA
- def other_funB(name,arc):
- print(name,arc)
- funB("http://c.biancheng.net")
- other_funB("Python教程:","http://c.biancheng.net/python")
C语言中文网: http://c.biancheng.net
Python教程: http://c.biancheng.net/python
- @funA
- @funB
- @funC
- def fun():
- #...
fun = funA( funB ( funC (fun) ) )
这里不再给出具体实例,有兴趣的读者可自行编写程序进行测试。
联系客服