Smooth python and cookbook learning notes (8), pythoncookbook
1. The default parameters of the function must be unchangeable.
If the default parameter of a function is a variable object, modification of the default parameter outside the function will also affect the function itself.
>>> Def spam (a, B = None): # variable parameters such as empty list [] cannot be used if B is an unchangeable parameter... if B is None :... B = []...
2. Anonymous Functions
1. You can use an anonymous function if you do not know the function name or want a short operation.
>>> Sum = lambda x, y: x + y >>>> sum (2, 3) 5 >>> def sum (x, y): # The above anonymous function, equivalent to this function... print (x + y)... >>> sum (3, 4) 7
2. bind variables to anonymous Functions
>>> X = 10 >>> a = lambda y: x + y >>>> x = 20 >>> B = lambda y: x + y> a (5) # found that not the expected 15, because x is changed by 25 >>> B (5) 25 >>> x = 25 >>> a = lambda y, x = x: x + y # bind x when defining, x is a local variable, not Affected by x changes> B = lambda y, x = x: x + y> a (5) 30> B (5) 20