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
...
>>> def test():
... a = {'name': 'wyj'}
... def f():
... return a['name']
... return a,f
...
>>> a,f = test()
>>> f()
'wyj'
>>> a['name'] = 'ljq'
>>> f()
'ljq'


对于python 函数嵌套

因为最后的那句return nested。

tester()()会自动调用它的返回值,而此时的返回值为nested,即def nested()这个函数,所以自然而然执行到了里面的print语句。
你可以试试把最后那就return nested改成其他的如return nestedxxx,再tester()()时就会报错了。
另外,在python里对于方法ester和nested是没有tester().nested()这种用法的,所以这样输入肯定报错的,如果ester和nested是类(class)的话才有这种写法。

希望对你有所帮助~~
 

python 里面类的__init__函数可以嵌套别的函数?

当然可以,查一下 “闭包 ”
 

评论关闭