Python函数嵌套实例

秋天的景色真美丽,像一幅美丽的图画。

在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函数嵌套实例请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战