#1#parameter contains only required parametersdeffunc (x, y): y.append (×)Print("%s"%y) func (1,[])#>>[1]Func (2,[])#>>[2]#2#parameter contains required and optional parameters, parameters with default values are optional#if the parameter default value is a Mutable object, the default parameter retains the modification of each function calldefFunc (x,y=[]): Y.append (x)Print("%s"%y) func (1)#>>[1]Func (2)#>>[1, 2]#to prevent this from happening, the default value is changed to None and the check code is added to the function bodydefFunc (x,y=None):ifY isnone:y=[] y.append (x)Print("%s"%y) func (1)#>>[1]Func (2)#>>[2]#3#function parameter invocation, there are two methods, one is to use positional parameters, one is to use the keyword parameterdeffoo (w,x,y,z):PassFoo (1,2,3,4) foo (1,2,Z=4,Y=3)#the order of parameters is not important when using keyword parameters#4#variable-length parameter list, using * and * * When defining functions#with *, all remaining parameters are placed as tuples in the args variable, and when other functions are called within a function, the args tuple is re-converted to the argument list and passed to the called function by using *argsdefFoo1 (x,*args):Print("foo1:p1=%s,p2=%s"%(X,args))defFoo (w,x,*args):Print("foo:p1=%s,p2=%s,p3=%s"%(W,x,args)) foo1 (x,*args) foo (1,2,3,4,5,6)#>>foo:p1=1,p2=2,p3= (3, 4, 5, 6)#>>foo1:p1=2,p2= (3, 4, 5, 6)#Use * * To put all remaining keyword arguments as dictionaries into the Kwargs variabledefFoo (w,x,**Kwargs):Print("foo:p1=%s,p2=%s,p3=%s"%(W,x,kwargs)) foo (1,x=2,y=3,z=4)#>>foo:p1=1,p2=2,p3={' y ': 3, ' Z ': 4}#use both * and * *defFoo (w,*args,**Kwargs):Print("foo:p1=%s,p2=%s,p3=%s"%(W,args,kwargs)) foo (1,2,3,y=4,z=5)#>>foo:p1=1,p2= (2, 3), p3={' y ': 4, ' Z ': 5}
Python learning Notes (functions)