简体   繁体   English

嵌套函数在Python中调用

[英]Nested Function calling in Python

def f1(): 
    X = 88
    def f2(): 
        print(X)
    return f2
action = f1() 
action()

Since f1 is returning f2 so it seems fine when I call f2 as (f1())() . 因为f1返回f2所以当我将f2称为(f1())()时似乎很好。

But when I call f2 directly as f2() , it gives error. 但是当我直接将f2()称为f2() ,它会给出错误。

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'f2' is not defined

Can someone explain what is the difference between the function calling of f2 using above 2 ways. 有人可以解释使用上述两种方式调用f2的函数之间的区别。

The function f2 is local to the scope of function f1 . 函数f2在函数f1的范围内是局部的。 Its name is only valid inside of that function because you defined it there. 它的名称仅在该函数内部有效,因为您在那里定义了它。 When you return f2 , all you are doing is giving the rest of the program access to the function's properties, not to its name . 当你返回f2 ,你所做的就是让程序的其余部分访问函数的属性,而不是它的名字 The function f1 returns something that prints 88 but does not expose the name f2 to the outer scope. 函数f1返回打印88的内容,但不将名称f2暴露给外部作用域。

Calling f2 indirectly through f1()() or action() is perfectly valid because those names are defined in that outer scope. 通过f1()()action()间接调用f2是完全有效的,因为这些名称是在该外部作用域中定义的。 The name f2 is not defined in the outer scope so calling it is a NameError . 名称f2未在外部作用域中定义,因此调用它是NameError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM