简体   繁体   中英

Argument binding in closure function

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

a = test()
a()

TypeError: nested() missing 1 required positional argument: 'x'

When I call nested to print argument x assigned in closure function test , the TypeError prompts me to pass a positional argument into nested, but why 'x' assigned in test function didn't be passed into nested?

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

a = test()
a()

The function namespace is inherited automatically, you don't have to pass it as an argument. If you include an argument into the function definition, then you have to obligatorily pass it a value when you call the function (unless you set a default value, for example:)

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

For the code you provide, I understand you kind of get the functioning of nested functions, but you fail to grasp the idea of namespaces. To tell from a namespace, a scope and a function/method argument, I recommend you some reading:

A scope refers to a region of a program where a namespace can be directly accessed, ie without using a namespace prefix. In other words: The scope of a name is the area of a program where this name can be unambiguously used, for example inside of a function. A name's namespace is identical to it's scope. Scopes are defined statically, but they are used dynamically.

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

You may find this other link useful: https://www.quora.com/What-is-the-difference-between-parameters-and-arguments-in-Python however best is always read Python docs for a precise and complete understanding ;)

When you do a = test() , you have called the test() function, and got the nested function. This function needs an argument, so you can't call it by a() alone (it's like calling it by nested() ). You would need to modify this to def nested() for your code to work, and, more importantly, to see that the function "remembers" the x defined outside.

A more typical example would be

def test(x):
    def nested(y):
    print(f'x is {x}, y is {y}')
return nested

a = test(5)
a(12)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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