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's function is The function's Please see the following code Result: Why did "a cut" output when neither The same goes for this code. Every time a function is called is not running. function foo () in the definition of first-class__object____code> rather than just a piece of code.
In other words, the definition of a function is evaluated as an object. p>
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.def a():
print "a excuted"
return 0
def b( x = a() ):
pass
a cut
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.def foo(a=[]):
a.append(5)
return a
: a [ ] continue once implemented, and maintain its value and is
.
Since then, calls the function
As the runs, a gets longer and longer.
© 2024 OneMinuteCode. All rights reserved.