This article example describes Python function parameter manipulation. Shared for your reference, as follows:
summarize
Functions in Python are simple to define, and they just have to fulfill the syntax formatting requirements. The caller only needs to be concerned with passing the right arguments and getting the right return value, and does not need to know the internal implementation of the function (unless he wants to learn and trace the source code).
That said, there is a great deal of flexibility for function definitions. In addition to the regular definition of mandatory parameters, default parameters, variable parameters, and keyword parameters are also supported. This makes it possible not only to handle complex parameters, but also to simplify the caller's code.
Formal and Real Parameters
There are two terms involved in almost every programming language, not just Python: parameter and argument, so what's the difference between them?
parameter refers to the argument in the function definition, while argument refers to the actual argument when the function is called.
Short description: parameter = formal parameter, argument = actual parameter.
For example, define a simple function:
>>> def greet(param1, param2): ... pass ... >>> >>> greet('Hello', 'Python')
where param1 and param2 are the formal parameters of the function, and in the functiongreet()
When called, the incoming ('Hello' respond in singing'Python') is then a real reference.
Functions with a fixed number of arguments
So far, all we've presented about functions is a fixed number of arguments. Let's look at a simple example:
>>> def greet(say, msg): ... print(say, msg) ... >>> >>> greet('Hello', 'Python') Hello Python
Here, the functiongreet()
With two arguments, calling this function with two arguments runs smoothly and without any errors.
What happens if, for example, the number of arguments does not match?
>>> greet() # No parameters ... TypeError: greet() missing 2 required positional arguments: 'say' and 'msg' >>> >>> greet('Hi') # There's only one parameter ... TypeError: greet() missing 1 required positional argument: 'msg'
Obviously, the interpreter will whine. But it's a cinch for Python to fix this problem, so read on!
default parameter
When defining a function, you can use the assignment operator (=) to specify a default value for an argument.
Note: If a parameter does not have a default value, you must specify a value for it when you call it; if a parameter has a default value, then the value is optional when you call it, and if you provide a value for it, it will override the default value.
>>> def greet(say, name = 'James', msg = 'I am your biggest fan!'): ... print(say, ',', name, ',', msg) ... >>> greet('Hi') # Mandatory parameters only Hi , James , I am your biggest fan! >>> >>> greet('Hi', 'Kobe') # Give 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 has no default value, it must be specified; name, 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, a non-default parameter cannot come after a default parameter.
For example, define the function above as:
def greet(name = 'James', say):
It would have triggered the error:
SyntaxError: non-default argument follows default argument
Keyword parameters
When a function is called with certain values, those values are assigned to the parameters according to their position.
For example, in the above functiongreet()
When using thegreet('Hi', 'Kobe')
When it is called, 'Hi' is assigned to the parameter say, and similarly, 'Kobe' is assigned to name.
Python allows the use ofkwarg = value
Format keyword arguments to call the function:
>>> def greet(say, name = 'James'): ... print(say, ',', name) ... >>> >>> greet(say = 'Hi', name = 'Kobe') # 2 keyword parameters Hi , Kobe >>> >>> greet(name = 'Kobe', say = 'Hi') # 2 keyword parameters (reverse order) Hi , Kobe >>> >>> greet('Hi', name = 'Kobe') # Location parameters mixed with keyword parameters Hi , Kobe
When a function is called in this way, the keyword argument must come after the positional argument, all passed keyword arguments must match one of the arguments accepted by the function, and their order does not matter.
For example, a call like the following will raise an error:
>>> greet(name = 'Kobe', 'Hi') # Keyword parameter before positional parameter ... SyntaxError: positional argument follows keyword argument >>> >>> greet('Hi', na = 'Kobe') # na mismatch ... TypeError: greet() got an unexpected keyword argument 'na'
Variable parameters
Variable parameters, also known as indeterminate-length parameters, are, as the name implies, passed in a variable number of parameters, which can be any number (0, 1, 2 ... N).
To define a variable parameter, simply add an asterisk before the parameter name (*
). Inside the function, these arguments are wrapped in atuple
。
Note: This * is not the same as *, and should not be mistaken for pointers in C/C++.
>>> def greet(*names): ... print(names) ... >>> >>> greet() # No arguments, return empty tuple () >>> >>> greet('Jordan', 'James', 'Kobe') ('Jordan', 'James', 'Kobe')
Sometimes it is necessary to use positional parameters as well as variable parameters in function definitions, but the positional parameters must always come before the variable parameters.
>>> 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 list of formal parameters because they collect all the remaining input parameters passed to the function. Any formal parameter that comes after a variable parameter is a "forced keyword" parameter, meaning that it can only be used as a keyword parameter, not a positional parameter.
>>> def greet(*names, sep = ','): ... return (names) ... >>> >>> greet('Jordan', 'James', 'Kobe') 'Jordan,James,Kobe' >>> >>> greet('Jordan', 'James', 'Kobe', sep = '/') # Used as a keyword argument 'Jordan/James/Kobe' >>> >>> greet('Jordan', 'James', 'Kobe', '/') # Used as a positional parameter 'Jordan,James,Kobe,/'
Arbitrary keyword parameters
There is also a mechanism for an arbitrary number of keyword arguments. To do this, use the double asterisk (**
):
>>> def greet(**all_star): ... print(all_star) ... >>> greet() # Returns the empty dictionary with no arguments {} >>> >>> greet(name = 'James', age = 18) {'name': 'James', 'age': 18}
When the last form is**msgs
appears, it receives a dictionary containing all the keyword arguments except those corresponding to the formal parameter. It can also be used with the*names
The combination of the formal parameter (*names
Must appear in**msgs
(Before).
For example, define a function like this:
>>> def greet(say, *names, **msgs): ... print('--', say) ... for name in names: ... print(name) ... print('-' * 40) ... keys = sorted(()) ... for key in keys: ... print(key, ':', msgs[key]) ... >>> >>> greet('Hi', 'Jordan', 'James', 'Kobe', msg = 'I want to challenge you!', challenger = 'Waleon') -- Hi Jordan James Kobe ---------------------------------------- challenger : Waleon msg : I want to challenge you!
Attention: Before the contents are printed, the msgs dictionary is passed through thekeys()
method's results are sorted to create a list of keyword parameter names. If this is not done, the order in which the parameters are printed is undefined.
Unpacking the parameters
As in the case of "variable parameters", it is also possible to use the*
operator. Except that in this case, unlike in the function definition of the*
The semantics of this are reversed, and the arguments will be unpacked instead of packed.
>>> def greet(name, age): ... print(name, age) ... >>> >>> t = ('James', 18) >>> greet(*t) James 18
There is another way, which hardly needs to be mentioned, and which is also wordy here:
>>> greet(t[0], t[1]) James 18
This invocation is clearly uncomfortable compared to unpacking. Also, in general, callinggreet(t[0], t[1])
It's almost futile, because the length is unknown. "Unknown" means that the length is only known at runtime, not when the script is written.
Similarly, dictionaries can be used with**
operator passes the keyword argument:
>>> def greet(name, age = 18): ... print(name, age) ... >>> >>> d = {'name':'James', 'age':32} >>> greet(**d) James 32
Python gets the number of function arguments:
Python 2.7 writeup:
# -*- coding:utf-8 -*- #! python2 def abc(a,b,c): print a,b yy=abc.func_code.co_argcount print yy
The output result is
3
python3.6 write method
# -*- coding:utf-8 -*- #! python3 def abc(a,b,c): print(a,b) a=abc.__code__.co_argcount print(a)
The output result is
3
Usage Scenarios:
For example, in the REST specification of the code, request data format checking, to determine whether the number of parameters to carry the number of parameters required to meet the function, not on the return error
Readers interested in more Python related content can check out this site's topic: theSummary of Python function usage tips》、《Summary of Python Math Operations Tips》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.