欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python函数嵌套实例

时间:2021-05-14 10:40:02|栏目: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代码

下一篇:python进程和线程用法知识点总结

本文标题:Python函数嵌套实例

本文地址:http://www.codeinn.net/misctech/121418.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有