python内嵌函数和装饰器函数返回值的区别
上一节当中,我们留了一个疑问,就是装饰器函数的内嵌函数的返回值若是内嵌函数的引用(加“()”)的话,将引发TypeError: 'NoneType' object is not callable错误,而一般情况下的内嵌函数却不会,为什么呢?我们来先看两个实例。
python内嵌函数
我们先来看一看python内嵌函数的实例。python内嵌函数,顾名思义就是函数内部再创建一个函数:
内嵌函数实例
def outer():
print('这是外部函数')
def inner():
print('这是内嵌函数')
return inner #返回函数名
——————————————————————————————————————
outer() #调用函数
运行结果:
这是外部函数
.inner()>
实例解析
如上代码,我们设计了一个outer函数和一个内嵌的inner函数,外部函数return返回的是inner函数名,根据运行的结果我们发现,该函数返回值是一个function,也就是一个函数,并没有调用。
接下来,我们来尝试一下返回函数的调用
def outer():
print('这是外部函数')
def inner():
print('这是内嵌函数')
return inner() #与上面的代码对比,返回函数的调用仅加了个英文的“()”
——————————————————————————————————
outer()
运行结果:
这是外部函数
这是内嵌函数
代码解析
如上例,返回函数的调用,那么在外层函数outer返回值的同时执行内嵌函数inner。
综上所述:内嵌函数的返回的函数名或函数的引用,并不会引发TypeError的错误。接下来我们来看一看装饰器的内嵌函数的返回值。
装饰器的内嵌函数
上一节中,我们在介绍多重装饰器的时候,使用了内嵌的函数,为了详细一点,我们先从“单重”的装饰器的内嵌函数来看一看。
装饰器内嵌函数实例
def outer(func):
def inner():
print('This is inner function')
func()
return inner()
@outer
def test():
print('This is test function')
——————————————————————————————
执行结果:
This is inner function
This is test function
代码解析
如上代码,我们在装饰器函数outer中返回了函数的调用inner(),从执行结果来看,装饰器很好地进行了工作,并没有引发TypeError的错误,而在多重装饰器当中,这将引发错误。
多重装饰器内嵌函数的返回值
实例
def outer(func):
def inner():
print('This is inner function')
func()
return inner()
def outer2(func):
def inner():
print('This is inner 2')
func()
return inner()
@outer
@outer2
def test():
print('This is test function')
——————————————————————————————————————————————————
test() #注意多重装饰器的函数调用
执行结果:
This is inner 2
This is test function
This is inner function
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-x> in <module>
10 return inner()
11 @outer
---> 12 @outer2
13 def test():
14 print('This is test function')
<ipython-input-x> in outer(func)
3 print('This is inner function')
4 func()
----> 5 return inner()
6 def outer2(func):
7 def inner():
<ipython-input-x> in inner()
2 def inner():
3 print('This is inner function')
----> 4 func()
5 return inner()
6 def outer2(func):
TypeError: 'NoneType' object is not callable
————————————————————————————————
当我们把return返回值的inner()的括号去掉,编程inner,在运行一下
执行结果:
This is inner function
This is inner 2
This is test function
代码解析
从上面代码中的错误报告,我们可以发现,当我们在多重装饰器的内嵌函数当中返回函数的引用时,将引发TypeError的错误。为什么会这样呢?嗯.......解释这个问题,应该就像解释python为什么要用int表示整型数据一样吧,这就是python的语法设计。
除此之外,我们也不难发现,上面两种情况所输出的内容顺序也是不一样的。第一个先输出“ This is inner 2”,第二个先输出的是“ This is inner function”。
python内嵌函数与装饰器内嵌函数返回值的区别就暂时介绍到这里,下一节我们将继续介绍python的读写,这在大数据当中应用得十分广泛。