In python, function parameters are defined in four ways:
- F (arg1, arg2 ,...)
This is the most common definition method. A function can define any parameter. Each parameter is separated by a comma, when calling a function defined in this way, you must provide the same number of values (actual parameters) in the parentheses after the function name, and the order must be the same, that is to say, in this call method, the number of form parameters and real parameters must be the same and must correspond one to one, that is, the first form parameter corresponds to the first real parameter. For example:
def a(x,y): print x,y
Call this function. If a () is used, x takes 1, y takes 2, and the form is used to correspond to the real parameters. If a (1) or a (, 3), an error is returned.
2. F (arg1, arg2 = value2 ,...)
This method is the first release version and provides the default value.
def a(x,y=3): print x,y
Call this function. a (1, 2) also returns x to take 1, y to take 2, but if a (1), no error will be reported. At this time, x is still 1, y is the default value of 3. The above two methods can also change the parameter location, such as a (y = 8, x = 3.
3. F (* arg1)
The preceding two methods are as follows, it adds a * parameter name to indicate that the number of real parameters of this function is not fixed. It may be 0 or n. Note that no matter how many parameters are stored in the function, they are stored in the tuple named identifier.
>>> def a(*x): if len(x)==0: print 'None' else: print x >>> a(1)
(1,) # store in tuples
>>> a() None >>> a(1,2,3) (1, 2, 3) >>> a(m=1,y=2,z=3)Traceback (most recent call last): File "<pyshell#16>", line 1, in -toplevel- a(m=1,y=2,z=3) TypeError: a() got an unexpected keyword argument 'm'
4. F (** arg1)
The first two parameters * are used to indicate that the parameters are stored in the dictionary in the form of identifiers. In this case, arg1 = value1 must be used to call the function, arg2 = value2.
>>> Def a (** x): if len (x) = 0: print 'none' else: print x >>> () none >>> a (x = 1, y = 2) {'y': 2, 'x': 1} # store it in the dictionary >>> a (1, 2) # Traceback (most recent call last): File "<pyshell #25>", line 1, in-toplevel-a (1, 2) TypeError: () takes exactly 0 arguments (2 given)