Why is the default variable disabled in the function definition?

I found an interesting problem why you are trying to do the following to call a golf code:

>>> f=lambda s,z=len(s): 5+z
>>> f("horse")
11                            #Expected 10
>>>              
>>> def g(s,z=len(s)):
...  print "z: ", z
...  print "sum: ", 5+z
...
>>> g("horse")
z:  6
sum:  11    
>>>                       
>>> len("horse") + 5           #Expected function operation
10 

Creating a function in both directions seems to be initializing zas 6instead of the expected 5, why is this happening?

+4
source share
3 answers

There is a page in python docs that explains this

Pythons default parameters are evaluated once when the function is not defined every time the function is called

s 6 -. python z=len(s), z=6. , .

+5

-, . s ​​ comment , z , s.

:

>>> a = 9
>>> f = lambda b: a + b
>>> f(3)
12
>>> a = 11
>>> f(3)
14
>>> f = lambda b, a=a: a + b # "a" gets bound to previous value 11
>>> f(3)
14
>>> a = 3 # 
>>> f(3)
14

, a=a a , .

- :

>>> f = lambda s: 5 + len(s)
>>> f('horse')
10
+2

Your function definition will not work because you have defined your default arguments. Pythons default parameters are evaluated once when a function is defined, and not every time when a function is called (for example, it says Ruby). This means that if you use the default mutable argument and mutate it, you will mutate this object for all future function calls. Your program will not work, as you see below!

enter image description here

0
source

Source: https://habr.com/ru/post/1623317/


All Articles