There are two special parameters when passing in parameters, *args,**kwargs, function as follows:
defFoo (*args, * *Kwargs):Print 'args =', argsPrint 'Kwargs =', KwargsPrint '---------------------------------------'if __name__=='__main__': foo (1,2,3,4) foo (a=1,b=2,c=3) foo (1,2,3,4, a=1,b=2,c=3) foo ('a', 1, None, A=1, b='2', c=3)
The output results are as follows:
args = (1, 2, 3, 4) Kwargs= {} ---------------------------------------args=() Kwargs= {'a': 1,'C': 3,'b': 2} ---------------------------------------args= (1, 2, 3, 4) Kwargs= {'a': 1,'C': 3,'b': 2} ---------------------------------------args= ('a', 1, None) Kwargs= {'a': 1,'C': 3,'b':'2'} ---------------------------------------
That is, *args is passed in a Tuple,*kwargs is passed in a dict.
Using this feature, we can mimic a switch keyword.
There is no similar in Python
Switch ():
Case 1:pass
Case 2:pass
This type of switch statement, so you want to convert it.
There are two ways of doing this.
(1) Lambda method, suitable for case is single statement:
switch={
' Case1 ': Lambda:pass,
' Case2 ': Lambda:pass,
' Case3 ': lambda:pass
}
switch[' Case1 '] ()
(2) Dict method, for case is a multiline statement or with parameters:
def switch (case, *args, **kwargs):
Def case1 (a):
Pass
Def Case2 (A, B):
Pass
Go ={
' Case1 ': case1,
' Case2 ': case2
}
Go[case] (*args, **kwargs)
switch (case, args)
Another point about Python parameters is that the default parameter is evaluated only once for the function definition (that is, the DEF statement is executed), and the previous value is used each time the function is called (reference function definitions). It can be concluded that when the default value of the default parameter is a Mutable object, if the function internal changes the default parameters, it will affect the next time the function is called the default value (in general, this may not be the behavior you want).
Shaped like
def FO (a,b=[]):
Pass
Each call to fo,b points to the same object
You can experiment with this:
def fo (a,b=[]): print(ID (b)) fo (1) fo(5) fo(10)
The results are all the same.
This feature can implement such a function, F (3) (2) (1) (0) = 6, which means that there is a function f (a) (b) (c) (0) =a+b+c when the incoming 0 o'clock is triggered.
def fo (a,b=[]): if(a==0): re=sum (b) b.clear () Return re else: b.append (a) return fo
[Python] about function incoming parameters