闭包函数中的参数绑定

-1 python closures arguments function

def test():
    x = 99
    def nested(x):
        print (x)
    return nested

a = test()
a()
Run Code Online (Sandbox Code Playgroud)

TypeError:nested()缺少1个必需的位置参数:'x'

当我调用nested在闭包函数中分配的print参数x时test,TypeError会提示我将位置参数传递给嵌套,但为什么在测试函数中分配的'x'没有传递给嵌套?

J. *_*nde 5

def test():
    x = 99
    def nested():
        print (x)
    return nested

a = test()
a()
Run Code Online (Sandbox Code Playgroud)

函数名称空间是自动继承的,您不必将其作为参数传递.如果在函数定义中包含一个参数,那么在调用函数时必须强制传递一个值(除非你设置了一个默认值,例如:)

def test():
    x = 99
    def nested(y=100):
        print (x,y)
    return nested

a = test()
a() # will prinnt 99,100 because x is already inheritted in the namespace, 
    # and 100 is the fallback value
Run Code Online (Sandbox Code Playgroud)

对于您提供的代码,我理解您可以获得嵌套函数的功能,但是您无法掌握命名空间的概念.要从命名空间,范​​围和函数/方法参数告诉,我建议您阅读一些内容:

范围是指程序的一个区域,其中可以直接访问命名空间,即不使用命名空间前缀.换句话说:名称的范围是程序的一个区域,可以明确地使用该名称,例如在函数内部.名称的名称空间与其范围相同.范围是静态定义的,但它们是动态使用的.

https://www.python-course.eu/namespaces.php

您可能会发现这个其他链接很有用:https: //www.quora.com/What-is-the-difference-between-parameters-and-arguments-in-Python但是最好总是阅读Python文档以获得准确和完整的理解;)