Python function parameter operation details

  • 2020-11-30 08:29:08
  • OfStack

This article illustrates the Python function parameter operation. To share for your reference, the details are as follows:

The paper

In Python, the function definition is simple enough to satisfy the corresponding syntax formatting requirements. For the caller, it's enough to focus on passing the correct parameters and getting the return value, without having to learn the internal implementation of the function (unless you want to learn and track the source code).

Having said that, there is a lot of flexibility in the definition of functions. In addition to the required parameters that are normally defined, default parameters, variable parameters, and keyword parameters are also supported. This way, you can not only handle complex parameters, but also simplify the caller's code.

Formal parameters and arguments

Not only Python, but almost all programming languages involve two terms: parameter and argument. So, what's the difference?

parameter refers to the parameters in the function definition, while argument refers to the actual parameters when the function is called.

Brief description: parameter = formal parameter (formal parameter), argument = argument (actual parameter).

For example, define a simple function:


>>> def greet(param1, param2):
...   pass
... 
>>> 
>>> greet('Hello', 'Python')

Where param1 and param2 are formal parameters of the function, while in the function greet() When called, the passed ('Hello' and 'Python') are arguments.

A function with a fixed number of arguments

So far, we've talked about functions with a fixed number of arguments. Take a look at a simple example:


>>> def greet(say, msg):
...   print(say, msg)
... 
>>> 
>>> greet('Hello', 'Python')
Hello Python

Here, the delta function greet() With two arguments, the function is called with two arguments, and it runs smoothly without any errors.

If the number of arguments does not match, what happens?


>>> greet() #  No parameters 
...
TypeError: greet() missing 2 required positional arguments: 'say' and 'msg'
>>> 
>>> greet('Hi') #  only 1 A parameter 
...
TypeError: greet() missing 1 required positional argument: 'msg'

Obviously, the interpreter will grumble. But for Python, solving this problem was a piece of cake. Read on!

The default parameters

When you define a function, you can use the assignment operator (=) to specify a default value for an argument.

Note: If the parameter does not have a default value, you must specify a value for it when invoked. If the parameter has a default value, the value is optional at call time, and if 1 value is provided for it, the default value is overridden.


>>> def greet(say, name = 'James', msg = 'I am your biggest fan!'):
...   print(say, ',', name, ',', msg)
... 
>>> greet('Hi') #  Only mandatory parameters are provided 
Hi , James , I am your biggest fan!
>>> 
>>> greet('Hi', 'Kobe') #  given 1 An optional parameter 
Hi , Kobe , I am your biggest fan!
>>> 
>>> greet('Hi', 'Kobe', 'I want to challenge you!') #  Give all the parameters 
Hi , Kobe , I want to challenge you!

Since say does not have a default value, it must be specified; name and msg have default values, so the values are optional.

All parameters in a function can have default values, but once a default parameter exists, all parameters to the right of it must also have default values. That is, non-default parameters cannot be followed by default parameters.

For example, define the above function as:


def greet(name = 'James', say):

It causes an error:

SyntaxError: non-default argument follows default argument

Keyword parameter

When a function is called with certain values, these values are assigned to parameters based on their position.

For example, in the above function greet() In, when used greet('Hi', 'Kobe') When it is called, 'Hi' is assigned to the parameter say, likewise, 'Kobe' is assigned to name.

Python is allowed kwarg = value Format the keyword argument to call the function:


>>> def greet(say, name = 'James'):
...   print(say, ',', name)
... 
>>> 
>>> greet(say = 'Hi', name = 'Kobe') # 2  Keywords parameters 
Hi , Kobe
>>> 
>>> greet(name = 'Kobe', say = 'Hi') # 2  Keywords parameters (out of order) 
Hi , Kobe
>>> 
>>> greet('Hi', name = 'Kobe') #  Position parameters are mixed with keyword parameters 
Hi , Kobe

When a function is called in this manner, the keyword arguments must follow the positional arguments, and all passed keyword arguments must match one of the arguments accepted by the function, and their order is not important.

For example, a call like this throws an error:


>>> greet(name = 'Kobe', 'Hi') #  The keyword parameter precedes the position parameter 
...
SyntaxError: positional argument follows keyword argument
>>>
>>> greet('Hi', na = 'Kobe') # na  Don't match 
...
TypeError: greet() got an unexpected keyword argument 'na'

Variable parameter

Variable parameters are also called indefinite parameters. As the name implies, the number of parameters passed in is variable, and can be any (0, 1, 2... N).

To define a variable parameter, simply add an asterisk ( * ). Inside the function, these parameters are wrapped as 1 tuple .

Note: This * is not that *, do not mistake it for a pointer in C/C++.


>>> def greet(*names):
...   print(names)
... 
>>> 
>>> greet() #  Returns an empty tuple with no arguments 
()
>>>
>>> greet('Jordan', 'James', 'Kobe')
('Jordan', 'James', 'Kobe')

Sometimes, you must use position arguments as well as variable arguments in a function definition, but the position argument must always precede the variable argument.


>>> def greet(say, *names):
...   print(say, names)
... 
>>> 
>>> greet('Hi')
Hi ()
>>> 
>>> greet('Hi', 'Jordan', 'James', 'Kobe')
Hi ('Jordan', 'James', 'Kobe')

Typically, variable parameters appear at the end of the parameter list because they collect all the remaining input parameters passed to the function. Any formal parameters that appear after a variable parameter are "mandatory keyword" parameters, meaning that they can only be used as keyword parameters and not as positional parameters.


>>> def greet(*names, sep = ','):
...   return sep.join(names)
... 
>>> 
>>> greet('Jordan', 'James', 'Kobe')
'Jordan,James,Kobe'
>>> 
>>> greet('Jordan', 'James', 'Kobe', sep = '/') #  Is used as a keyword parameter 
'Jordan/James/Kobe'
>>>
>>> greet('Jordan', 'James', 'Kobe', '/') #  Used as a location parameter 
'Jordan,James,Kobe,/'

Arbitrary keyword arguments

There is also a mechanism for any number of keyword arguments. To do this, double star ( ** ) :


>>> def greet(say, msg):
...   print(say, msg)
... 
>>> 
>>> greet('Hello', 'Python')
Hello Python

0

When the last form is **msgs When the parameter appears, it receives a dictionary containing all the keyword arguments except those corresponding to the parameter. Can also with *names Is a combination of formal parameters ( *names Must be present at **msgs Before).

For example, define a function like this:


>>> def greet(say, msg):
...   print(say, msg)
... 
>>> 
>>> greet('Hello', 'Python')
Hello Python

1

Note: Before printing the content, pass the msgs dictionary keys() Method to sort the results to create a list of keyword parameter names. If this is not done, the order in which the parameters are printed is undefined.

Unpack the parameters

Just like "variable arguments", it can also be used in function calls * Operators. But in this case, and in the function definition * Instead, the parameters will be unpacked rather than packaged.


>>> def greet(say, msg):
...   print(say, msg)
... 
>>> 
>>> greet('Hello', 'Python')
Hello Python

2

There is another way, which is hardly necessary to mention, and it is also wordy here 1:


>>> greet(t[0], t[1])
James 18

Compared to unpacking, this method of calling is obviously uncomfortable. In addition, in 1 general case, call greet(t[0], t[1]) Almost in vain, because the length is unknown. "Unknown" means that the length is only known at run time, not at script time.

In the same way, a dictionary can be used ** Operator to pass keyword arguments:


>>> def greet(say, msg):
...   print(say, msg)
... 
>>> 
>>> greet('Hello', 'Python')
Hello Python

4

Python Gets the number of function parameters:

Python2. 7 writing:


>>> def greet(say, msg):
...   print(say, msg)
... 
>>> 
>>> greet('Hello', 'Python')
Hello Python

5

The output result is

[

3

]

python3. 6


>>> def greet(say, msg):
...   print(say, msg)
... 
>>> 
>>> greet('Hello', 'Python')
Hello Python

6

The output result is

[

3

]

Usage Scenario:

For example, in the code of REST specification, request data format test can determine whether the number of parameters carried conforms to the number of parameters required by this function, so return error can not be used

For more information about Python, please refer to Python Functions, Python Mathematical Operation Techniques, Python Data Structure and Algorithm, Python String Operation Techniques, and Python Introductory and Advanced Classics.

I hope this article has been helpful to you in Python programming.


Related articles: