仅当一个函数需要嵌套函数时,它是一种好方法吗? [英] Is nested function a good approach when required by only one function?

查看:75
本文介绍了仅当一个函数需要嵌套函数时,它是一种好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,函数A 仅由函数B 所需要,是否应在B内定义A? / p>

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

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

def method_b(arg):
返回some_data

在Python中我们可以声明 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(arg)

还是应该避免这样做?

解决方案

 >>> def sum(x,y):
... def do_it():
...返回x + y
...返回do_it
...
>>> a = sum(1,3)
>>
<函数do_it at 0xb772b304>
>> a()
4

这是您要找的东西吗?称为关闭


Let's say that a function A is required only by function B, should A be defined inside B?

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(arg)

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天全站免登陆