Python函数嵌套的例子

有关Python函数嵌套的实例,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

... www.jbxue.com

>>> def test():

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

... def f():

... return a['name']

... return a,f

...

>>> a,f = test()

>>> f()

'wyj'

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

>>> f()

'ljq'

 

你可能感兴趣的:(python)