Function parameter type, usage and code sample

In programming languages, a function will be defined as a function, can be called repeatedly, but not always the same code is repeated, this embodiment can significantly reduce the complexity of the code.

1. Basic

Defined functions when we can take parameters, may not take parameters, return values ​​can also be no return value (does not return the default value is None).

# Takes no parameters and returns no value 
DEF func1 ():
     Print ( " ! This IS A function " ) 

# function parameters, no return value, parameters a, b is the location parameter function 
DEF func2 (a, b ):
     Print ( " the Result: " , a * B) 

# return value of the function 
DEF func3 (a, B):
     Print ( " the Result: " , a * B)
     return a * B

Call functions according to the order of the incoming parameters, call format and output:

>>>func1()
This is a function!
>>>func2(2,3)
Result:6
>>>r = func3(2,3)
Result:6

When we defined functions, sometimes a parameter is often the same value, then we can set such parameters as the default parameters. For example, function function is to calculate a number of arbitrary power, we very much are square, then we can power this parameter is set to default to 2, then if it is calculating the square, this parameter when calling the function on you can not pass. When the function has a plurality of parameters, the large change parameter generally put in front of, behind the discharge small parameter changes. Small changes in parameters can be used as the default parameters.

# N-default parameters, the default is 2 
DEF Func4 (X, = n-2 ): 
    R & lt =. 1
     for I in Range (n-): 
        R & lt = R & lt * X
     Print (R & lt)

If you do not pass the parameter, then the default is the default value for the time parameters, called; if passed parameter, you can directly transfer value can also be written in the format defined: Parameter value =

>>>func4(3)
9
>>>func4(3,4)
81
>>>func4(3,n=4)
81

 

2. Variable parameters

For the position of the mentioned parameters, a fixed number of parameters must be passed at the time of the call. And we often encounter a number of requirements such as the product of the number of issues such as the number of advance may be uncertain parameters. Then we can define the variable parameters, i.e. the number of parameters is not fixed, and may be 0, 1 or any number.

Computing the product of a set of numbers, we can first list consisting of the set of numbers or tuple type, the calling function.

# Numbers may be a list or tuple, the number of elements is arbitrary 
DEF Func5 (Numbers):
     IF len (Numbers): 
        R & lt =. 1
         for I in Numbers: 
            R & lt * = I
         Print (R & lt)
     the else :
         Print (None)
>>>func5([1,2,3,4,5])
120
>>>func5((1,2,3,4,5))
120
>>>func5([])
None
>>>func5(())
None

The above parameters need to be list or tuple, then how can simplify the molding such as: Func5 (1,2,3,4,5 ) format call it?

The answer is: through the front parameters when defining plus *, the code does not need to make any changes.

Well, this time received parameter is a tuple

We add an asterisk, defined as func6, namely func6 (* numbers) in front of the numbers of parameters func5. In this case in the form of parameters can be simplified. For originally list or tuple type variable before the variable corresponding to the list with * or to the tuple element becomes variable parameters passed into the function is called.

 

Func6 >>> (1,2,3,4,5 )
 120 
>>> Func6 () 
None 
>>> NUM = [1,2,3,4,5] # define a list
>>> func6 (* num )
120
>>> Func6 (NUM * [: 2]) also list the slice #
2

 

 

3. keyword arguments

We fill in the information when registering an account, and some is optional, so for developers, do not fill these variables is None, and the number is uncertain. Under circumstances such as this, there is a key parameter can come in handy. Keyword parameter allows any number of incoming or 0 with a parameter name of the parameter, these parameters are automatically assembled as keywords inside a dict function. Keyword arguments with the ** kw generally defined parameter names can be customized, but the practice of using this, we can use this.

# Keyword arguments 
DEF Func7 (name, Age, ** kw):
     Print ( ' name: ' , name, ' Age: ' , Age, ' OTHER: ' , kw)

Keywords can pass any number of arguments when you call, when you type a dict variable as keyword arguments, before the variable plus ** can be.

>>>func7('Michael', 30)
name: Michael age: 30 other: {}
>>>func7('Michael', 30, city='Beijing')
name: Michael age: 30 other: {'city': 'Beijing'}
>>>func7('Michael', 30, city='Beijing', job='teacher')
name: Michael age: 30 other: {'city': 'Beijing', 'job': 'teacher'}

>>>per1 = {'city':'Beijing', 'job':'teacher'}
>>>func7('Michael', 30, **per1)
name: Michael age: 30 other: {'city': 'Beijing', 'job': 'teacher'}

 

4. Name the key parameters

Keyword arguments, keyword arguments can be passed to any unrestricted function call. As to what passed in the end, you need to check kw within the function. If you need to specify or limit the parameters passed in the name parameter, then use the named keyword arguments, by definition, it is the key parameter names. For example, receive only the name and age.

** kw different keywords and parameters, named keyword arguments require a special separator asterisk, asterisk behind the argument is treated as named keyword arguments.

# Behind the asterisk parameter is named keyword arguments 
DEF Func8 (name, Age, * , City, the Job):
     Print (name, Age, City, the Job)

Keyword parameters must be passed in the parameter name = parameter is specified, otherwise it will error.

Func8 >>> ( ' Jack ' , 24, City = ' Beijing ' , Job = ' Engineer ' ) 
Jack 24 Beijing Engineer
 >>> Person ( ' Jack ' , 24, City = ' Beijing ' , Job = ' Engineer ' , = Sex ' Meal ' ) 
being given, can not pass parameter other than the keyword parameter named

If the function has been defined in a variable parameter, followed later named keyword arguments no longer need a special separator * a.

# * Args is a variable parameter, after the keyword parameter so city, job does not need the special separator asterisk 
DEF Func9 (name, Age, * args, city, job):
     Print (name, Age, * args, city, job)
<<<func9('Jack', 24, 'placehold', city='Beijing', job='Engineer')
Jack 24 placehold Beijing Engineer
<<<func9('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer

Parameters related to the composition herein, the definition of a sequence of parameters: location parameter, the variable parameter, the parameter name keyword, the keyword parameter.

Good understanding of the two functions is called and the following results.

# Position parameter, default parameter, the variable parameter, the keyword parameter combination 
DEF F1 (A, B, C = 0, * args, ** kW):
     Print ( ' A = ' , A, ' B = ' , B, ' C = ' , C, ' args = ' , args, ' kW = ' , kW) 

# positional parameters, the default parameters, parameter named keyword, the keyword parameter combination 
DEF F2 (A, B, C = 0, *, D, ** kW):
     Print ( ' A = ' , A, ' B = ' , B, ' C = ' , C, ' D =' , D ' = feet , feet)
>>>f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>>f1(1, 2, 3)
a = 1 b = 2 c = 3 args = () kw = {}
>>>f1(1, 2, 'placehold')
a = 1 b = 2 c = placehold args = () kw = {}
>>>f1(1, 2, 3, 'placehold')
a = 1 b = 2 c = 3 args = ('placehold',) kw = {}
>>>f1(1, 2, x='%')
a = 1 b = 2 c = 0 args = () kw = {'x': '%'}
>>>f1(1, 2, x='%', y='&')
a = 1 b = 2 c = 0 args = () kw = {'x': '%', 'y' :'&'}
>>>f1(1, 2, 'a', 'b', x='%', y='&')
a = 1 b = 2 c = a args = (') = {feet'b'x': '%', 'y' :'&'}
>>>f1(1, 2, 3, 'a', 'b', x='%', y=None)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': '%', 'y':} None 

can also tuple and a dict#
>>>args = (1, 2, 3, 4)
>>>kw = {'d': 99, 'x': '#'}
>>>f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}
>>>args = (1, 2, 3)
>>>f1(*args, **kw)
a = 1 b = 2 c = 3 args = () kw = {'d': 99, 'x': '#'}
>>>f2(*args, **kw)
a = 1 b = 2 c = 3 d = 99 kw = {'x': '#'}

 

Guess you like

Origin www.cnblogs.com/taotingz/p/11329771.html