Constructing a function of any number of acceptable parameters.
In order to allow a function that takes an arbitrary number of location parameters, a * parameter may be used. E.g:
def avg(first, *rest):
return (first + sum(rest)) / (1 + len(rest))
# Sample use
avg(1, 2) # 1.5
avg(1, 2, 3, 4) # 2.5
In this example, rest tuple parameters of all the other positions thereof. Then we regard it as the code to perform a sequence of subsequent calculations.
In order to receive any number of keyword arguments, beginning with the use of a ** parameters. such as:
import html
def make_element(name, value, **attrs):
keyvals = [' %s="%s"' % item for item in attrs.items()]
attr_str = ''.join(keyvals)
element = '<{name}{attrs}>{value}</{name}>'.format(
name=name,
attrs=attr_str,
value=html.escape(value))
return element
# Example
# Creates '<item size="large" quantity="6">Albatross</item>'
make_element('item', 'Albatross', size='large', quantity=6)
# Creates '<p><spam></p>'
make_element('p', '<spam>')
Here, attrs is a dictionary of all incoming coming keyword arguments included.
If you want a function can also accept an arbitrary number of positional parameters and keyword parameters, you can use * and ** the same time. such as:
def anyargs(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict
When using this function, all the parameters will be placed in the position of the tuple args, all keyword arguments will be placed in the dictionary kwargs.
A * parameter can appear in the function definition a position behind the last parameter, and ** parameters appear only in the last parameter. One thing to note is that in the * parameter is still behind other parameters can be defined.
def a(x, *args, y):
pass
def b(x, *args, y, **kwargs):
pass