标签: nested-function

嵌套函数中的变量范围

有人可以解释为什么以下程序失败:

def g(f):
  for _ in range(10):
    f()

def main():
  x = 10
  def f():
    print x
    x = x + 1
  g(f)

if __name__ == '__main__':
  main()
Run Code Online (Sandbox Code Playgroud)

随着消息:

Traceback (most recent call last):
  File "a.py", line 13, in <module>
    main()
  File "a.py", line 10, in main
    g(f)
  File "a.py", line 3, in g
    f()
  File "a.py", line 8, in f
    print x
UnboundLocalError: local variable 'x' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

但是,如果我只是将变量更改为x数组,它的工作原理如下:

def g(f):
  for _ in range(10):
    f() …
Run Code Online (Sandbox Code Playgroud)

python scope nested-function

6
推荐指数
1
解决办法
295
查看次数

嵌套函数如何在MATLAB中工作?

所以,我正在申请一份工作,需要弄清楚嵌套函数的工作原理.更具体地说,我想知道gnovice发布的以下示例是如何工作的.

问题是:

给定以下函数,在命令窗口中输入下面的代码时输出是什么?

function fcnHandle = counter
  value = 0;
  function currentValue = increment
    value = value+1;
    currentValue = value;
  end
  fcnHandle = @increment;
end

f1 = counter();
f2 = counter();
output = [f1() f1() f2() f1() f2()];  %# WHAT IS IT?!
Run Code Online (Sandbox Code Playgroud)

我不是在申请工作,而是能够找到问题的答案.我也发现了答案,从穆赫辛这个问题直观(找到一个矩阵的大小而不调用内置函数).但是,我忍不住在脑海中听到阿尔伯特爱因斯坦的声音.

在此输入图像描述

我认为文档有点乱,所以如果有人能够解释它是如何工作的,我会很高兴.

matlab nested-function

6
推荐指数
2
解决办法
663
查看次数

尽管使用++,循环计数器"呈指数增长"

背景资料

我正在设置一个函数,它根据开始日期和结束日期创建日期数组.

该函数将接收开始日期和结束日期,这些日期首先被格式化为year-month-dayT12:00:00:00格式化,然后使用.getTime()格式转换为毫秒.

我的剧本

我已经创建了以下脚本来创建数组.

var $date_array = [];

function calc_workdays_between_dates (a, b) {

    function $create_date_array ($start_date, $end_date) {

        var $counter    = 0;

        while ($start_date !== $end_date) {

            var x = new Date($start_date);

            x.setDate(x.getDate() + $counter);
            $date_array.push(x);
            $start_date = x.getTime();
            $counter++; 
        }
    }

    $create_date_array (a, b);
}
Run Code Online (Sandbox Code Playgroud)

请注意,在$create_date_array函数内部嵌套函数是有原因的$calc_workdays_between_dates.现在我已经删除了$calc_workdays_between_dates函数的所有其他部分,只关注手头的问题(我也在这个剥离版本上运行我的测试 - 所以函数的其余部分不会影响任何东西).

我的问题

例1:

如果我调用函数在calc_workdays_between_dates (x1, x2);哪里:

x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 …
Run Code Online (Sandbox Code Playgroud)

javascript counter while-loop nested-function

6
推荐指数
1
解决办法
306
查看次数

使用自由变量警告每个(嵌套)函数(递归)

我想做以下事情:

for every nested function f anywhere in this_py_file:
    if has_free_variables(f):
        print warning
Run Code Online (Sandbox Code Playgroud)

为什么?主要是作为对其他地方描述的后期约束关闭的保险.即:

>>> def outer():
...     rr = []
...     for i in range(3):
...         def inner():
...             print i
...         rr.append(inner)
...     return rr
... 
>>> for f in outer(): f()
... 
2
2
2
>>> 
Run Code Online (Sandbox Code Playgroud)

每当我收到有关自由变量的警告时,我都会添加一个显式异常(在极少数情况下我会想要这种行为)或者像这样修复它:

...         def inner(i=i):

然后,行为变得更像Java中的嵌套类(其中任何要在内部类中使用的变量必须是final).

(据我所知,除了解决后期绑定问题之外,这还会促进更好地使用内存,因为如果函数"关闭"外部作用域中的某些变量,那么外部作用域不能被垃圾收集因为功能就在附近.对吗?)

我找不到任何方法来获取嵌套在其他函数中的函数.目前,我能想到的最好的方法是使用解析器,这看起来很多工作.

python reflection closures nested-function

6
推荐指数
1
解决办法
396
查看次数

在功能性 React 组件中定义处理程序的正确方法?

据我所知,在 JavaScript 中定义函数有三种方式。

1. 声明

function handleEvent(e) {}
Run Code Online (Sandbox Code Playgroud)

2. 分配

var handleEvent = function(e) {}
Run Code Online (Sandbox Code Playgroud)

3. 箭头

var handleEvent = (e) => {}
Run Code Online (Sandbox Code Playgroud)

我一直在寻找有关这些选项中哪个是在功能性 React 组件中声明处理程序的首选方式的信息。我发现的所有文章都讨论了类组件、绑定等。但是随着新Hooks 的出现,在函数内部也必须有定义它们的标准。(毕竟,无论如何,功能组件一直存在。)

考虑以下组件,它声明了三个处理程序,它们是您在 React 组件中可能需要的不同行为的示例。

function NameForm(props) {
    const [inputName, setInputName] = useState("");

    useEffect(() => setInputName(props.initialValue), [props.initialValue]);

    const handleInputChange = function(event) {
        setInputName(event.target.value);
    };

    const resetForm = function() {
        setInputName(props.initialValue);
        props.onReset();
    };

    const handleFormSubmit = function(event) {
        event.preventDefault();
        props.onSubmit(inputName);
        resetForm();
    };

    /* React-Bootstrap simple form example using these handlers. */
    return (
        <Form …
Run Code Online (Sandbox Code Playgroud)

javascript function nested-function reactjs react-hooks

6
推荐指数
2
解决办法
2803
查看次数

从Python中的双嵌套函数中访问变量

以下代码:

x = 0
print "Initialization: ", x
def f1():
    x = 1
    print "In f1 before f2:", x
    def f2():
        global x
        x = 2
        print "In f2:          ", x
    f2()
    print "In f1 after f2: ", x
f1()
print "Final:          ", x
Run Code Online (Sandbox Code Playgroud)

打印:

Initialization:  0
In f1 before f2: 1
In f2:           2
In f1 after f2:  1
Final:           2
Run Code Online (Sandbox Code Playgroud)

有没有办法f2访问f1变量?

python global-variables nested-function

5
推荐指数
2
解决办法
2033
查看次数

使用C预处理器确定当前范围?

我正在使用C/Objective-C开发一个应用程序(请不要使用C++,我已经有了解决方案),我遇到了一个有趣的用例.

因为clang不支持嵌套函数,所以我的原始方法不起作用:

#define CREATE_STATIC_VAR(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }
Run Code Online (Sandbox Code Playgroud)

这段代码可以用GCC编译好,但由于clang不支持嵌套函数,我得到一个编译错误:

预期';' 在宣言结束时.

所以,我找到了一个适用于Clang函数内部变量的解决方案:

#define CREATE_STATIC_VAR_LOCAL(Type, Name, Dflt) static Type Name; ^{ /* loading code here */ }(); // anonymous block usage
Run Code Online (Sandbox Code Playgroud)

但是,我想知道是否有办法利用宏连接来为情况选择合适的方法,例如:

#define CREATE_STATIC_VAR_GLOBAL(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }
#define CREATE_STATIC_VAR_LOCAL(Type, Name, …
Run Code Online (Sandbox Code Playgroud)

scope global-variables static-variables clang nested-function

5
推荐指数
1
解决办法
1064
查看次数

CL中的辅助嵌套函数

我曾经在Haskell中编写嵌套的辅助函数(其中,顺便说一下,使用外部函数的参数并且是递归的),就像这样(loop):

sum a b = let
  loop s i = if i > b then s else loop (s + i) (i + 1)
  in loop 0 a
Run Code Online (Sandbox Code Playgroud)

Common Lisp中最清晰的模拟是什么?

我在这里搜索并发现一些讨论集中在从函数返回函数(以及在尝试调用这样的"返回"函数时可能出现的问题),这是不完全相同的情况,据我所知.

common-lisp nested-function

5
推荐指数
1
解决办法
2616
查看次数

嵌套函数的好处是什么(一般来说/在Swift中)

我刚刚学习了一些Swift,我遇到了关于嵌套函数的部分:

函数可以嵌套.嵌套函数可以访问外部函数中声明的变量.您可以使用嵌套函数来组织长或复杂函数中的代码.

这里开始

因此,如果声称的好处是"组织代码",为什么不在外部函数之外独立地拥有嵌套函数?对我来说,这看起来更有条理.

我能辨别的唯一好处是你"可以访问在外部函数中声明的变量",但与嵌套函数的混乱相比,这似乎微不足道.

有什么想法吗?

conventions function code-organization nested-function swift

5
推荐指数
1
解决办法
1652
查看次数

替换嵌套函数

我创建了一个ac程序,它使用了gnu扩展中的嵌套函数,现在我想让它们符合ansi c标准.

什么是转换嵌套函数的最佳方法,嵌套函数访问一些外部变量到不同的东西.

#define lambda(return_type, function_body) \
({ \
    return_type __fn__ function_body \
    __fn__; \
})
Run Code Online (Sandbox Code Playgroud)

示例用法

size_t var1;
size_t var2;
lambda(void, (...) {
    // some code
    lambda(void, (...) {
        // ...
        // do something with var1/var2
        // ..
    }

    // ...
    // do something with var1/var2
}
Run Code Online (Sandbox Code Playgroud)

我考虑过将变量移到全局范围,所以从每个"lambda"中都可以知道它们可能是最简单的解决方案,但我不想要考虑全局范围,我不确定,如果这是最干净的方式.


正如一些评论者所说 - 这是一个具体的例子

/* fill itt*/
int n_method = 0;
void *add_method = lambda(void, (ir_entity *method) {
    int itable_offset = n_method++;
    const char *method_name = get_entity_name(method);

    ir_entity *implementation = get_method_entity(klass, method_name); …
Run Code Online (Sandbox Code Playgroud)

c c99 nested-function

5
推荐指数
1
解决办法
158
查看次数