&[18] Parameters of Python functions

Posted by ninib on Sun, 07 Nov 2021 19:58:51 +0100


Pure smile: http://www.ityouknow.com/python.html

Defining a function is very simple, but how to define a function, what parameters are required, and how to call it are issues we need to think about.

Like most languages (such as Java), Python also provides a variety of parameter settings (such as default value parameters, keyword parameters, formal parameters, etc.). The code defined by these parameters can make us adapt to different open scenarios and simplify our code development.

Default value parameter

We create a function. After one or more of the defined parameters are given default values, we can call this function with fewer parameters than allowed, for example (Note: the following code uses Python version 3.7):

def def_param_fun(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')

# We can call it as follows
def_param_fun('Do you really want to quit?')

# def_param_fun('Do you really want to quit?', 2)
# def_param_fun('Do you really want to quit?', 2, 'Please, yes or no!')

As shown above, we can use one or more parameters to call this function. In our actual production, function parameters will be given default values in many cases. Therefore, the rational use of this parameter form can simplify a lot of our workload.

Important: when using the default value parameter, if our default value is a variable object, we may call the function with results that do not meet our expectations

As follows:

def f(a, l=[]):
    return l

# The function is called

# Return value
# [1]
# [1, 2]
# [1, 2, 3]

This is because the default value of the function is executed only once during initialization. Therefore, when the default value is a variable object (list, dictionary and most class instances), we can operate as follows:

def f(a, l=None):
    if l is None:
        l = []
    return l

# Call the function again

# Return value
# [1]
# [2]
# [3]

Variable parameters

Variable parameters, that is, we can change one or more parameters defined in the function, where * args means that a list or tuple can be passed in, and * * args means that a dict can be passed in. for instance:

def variable_fun(kind, *arguments, **keywords):
    print("friend : ", kind, ";")
    print("-" * 40)
    for arg in arguments:
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

# function call
             "hello xiaoming", "nice to meet you!",
             son="see you")

# output

friend :  xiaoming ;
hello xiaoming
nice to meet you!
mother : xiaoma
father : xiaoba
son : see you

We can also call in the following way to get the same result as above:

list01 = ["hello xiaoming", "nice to meet you!"]
dict01 = {'mother': 'xiaoma', 'father': 'xiaoba', 'son': 'see you'}
variable_fun("xiaoming", *list01, **dict01)

The above is actually the unpacking operation of python, which is similar to java.

Keyword parameters

Keyword parameters allow you to pass in 0 or any parameter with parameter name when calling a function, which allows us to call parameters flexibly. for instance:

# Borrow the official website example
def key_fun(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This key_fun wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

# function call  
key_fun(1000)                                          # 1 positional argument
key_fun(voltage=1000)                                  # 1 keyword argument
key_fun(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
key_fun(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
key_fun('a million', 'bereft of life', 'jump')         # 3 positional arguments
key_fun('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

Note that the value cannot be transferred repeatedly, otherwise the following error will be reported:

# TypeError: key_fun() got multiple values for argument 'voltage'
key_fun(100, voltage=1000)                             # error

Topics: Python