Python函数嵌套实例
Python函数嵌套实例
发布时间:2016-12-28 来源:查字典编辑
摘要:在Python中函数可以作为参数进行传递,而也可以赋值给其他变量(类似Javascript,或者C/C++中的函数指针);类似Javascr...

在Python中函数可以作为参数进行传递,而也可以赋值给其他变量(类似Javascript,或者C/C++中的函数指针);

类似Javascript,Python支持函数嵌套,Javascript嵌套函数的应用模式对Python适用;

复制代码 代码如下:

>>> def multiplier(factor):

... def multiple(number):

... return number * factor

... return multiple

...

>>>

>>> multiplier(3)(3)

9

>>> multiplier(4)(3)

与嵌套函数紧密相关的就是闭包特性,举一个简单的例子:

复制代码 代码如下:

>>> def test():

... a = {'name': 'wyj'}

... def f():

... return a['name']

... return f

...

>>> def test():

... a = {'name': 'wyj'}

... def f():

... return a['name']

... return a,f

...

>>> a,f = test()

>>> f()

'wyj'

>>> a['name'] = 'ljq'

>>> f()

'ljq'

例子3

#! /usr/bin/python def yao1(a=1,b=32): def yao2(c=54): def yao3(d=3): def yao4(e=10): return a+b+c+d+e return yao4 return yao3 return yao2 print yao1()()()()

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新python学习
热门python学习
脚本专栏子分类