函数内部函数 [英] function inside function

查看:104
本文介绍了函数内部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的例子。两种方法,一种从另一种调用:

  def method_a(arg):
some_data = method_b(arg)

def method_b(arg):
return some_data

可以在另一个 def 中声明 def 。所以,如果 method_b 是必需的,并且只从 method_a 调用,我应该声明 method_b 里面 method_a ?像这样:

  def method_a(arg):

def method_b(arg):
return some_data

some_data = method_b

还是应该避免这样做?

解决方案

 >>> def sum(x,y):
... def do_it():
... return x + y
... return do_it
...
>>> a = sum(1,3)
>>> a
< function do_it at 0xb772b304>
>>>>这是您在寻找什么?这是您需要的产品吗?它被称为关闭


Simple example. Two methods, one called from another:

def method_a(arg):
    some_data = method_b(arg)

def method_b(arg):
    return some_data

In Python we can declare def inside another def. So, if method_b is required for and called only from method_a, should I declare method_b inside method_a? like this :

def method_a(arg):

    def method_b(arg):
        return some_data

    some_data = method_b

Or should I avoid doing this?

解决方案

>>> def sum(x, y):
...     def do_it():
...             return x + y
...     return do_it
... 
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()
4

Is this what you were looking for? It's called a closure.

这篇关于函数内部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆