The default argument value keeps changing

Asked 2 years ago, Updated 2 years ago, 63 views

I thought the code below would always return [5] The price keeps changing.

I thought a=[] would be executed whenever foo() was executed, but is it not? What is happening in foo()?

def foo(a=[]):
    a.append(5)
    return a

Run:

>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]
>>> foo()

python language-design least-astonishment

2022-09-22 22:31

1 Answers

Python's function is first-class__object____code> rather than just a piece of code. In other words, the definition of a function is evaluated as an object.

The function's default parameter is bound to the function's definition, not its execution. Therefore, the default parameter can be written like member data, and the state can be changed every time a function is called.

Please see the following code

def a():
    print "a excuted"
    return 0

def b( x = a() ):
    pass

Result: a cut

Why did "a cut" output when neither a() nor b() were called? This is because in defb(x = a():, the default parameter x is bound to the definition. We didn't run the code like b(), but we initialized x in the definition of the function.

The same goes for this code.

def foo(a=[]):
    a.append(5)
    return a

Every time a function is called

is not running.

function foo () in the definition of : a [ ] continue once implemented, and maintain its value and is . Since then, calls the function

every time.

As the runs, a gets longer and longer.


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.