Zero-based entry python3.7-summary of basic knowledge (12) function upgrade

In addition to passing arguments in function calls in Python. Passing keywords. In addition to the default parameters, the following parameter transmission methods are provided.

One. variable parameter

As the name implies, variable parameters are the number of parameters that can be changed, and can be any one or more. Because the number of parameters is uncertain, we need to define the actual parameters as lists or tuples.

def sun(arr):
    add_data = 0
    for i in arr:
        add_data += i
    return add_data

a = sun((1, 2, 3, 4, 5))
print(a)
b = sun([1, 2, 3, 4, 5])
print(b)

c = sun([1, 2, 3])
print(c)
d = sun((1, 2, 3))
print(d)

We can find that when we pass in a list of unequal number of elements and tuples in the function call, we can get the correct result. This is the use of variable parameters.

Not only are these variable parameters shorthand. See example

def sun(*arr):
    add_data = 0
    for i in arr:
        add_data += i
    return add_data

a = sun(1, 2, 3, 4, 5)
print(a)

c = sun(1, 2, 3)
print(c)

At this time, we found that we only need to add "*" in front of the formal parameters to call the function without worrying about whether it is a list or tuple. Can still get the corresponding results correctly. This way of writing will not throw an exception even if no parameter code is passed.

def sun(*arr):
    add_data = 0
    for i in arr:
        add_data += i
    return add_data

a = sun()
print(a)

0

Looking at a new situation. Assuming that the formal parameters are preceded by "*", when I call the function, the actual parameters and a list or tuple. What happens if you directly pass this list or tuple directly into it.

def sun(*arr):
    add_data = 0
    for i in arr:
        add_data += i
    return add_data

a = sun((1, 2, 3, 4))
print(a)

Traceback (most recent call last):
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 7, in <module>
    a = sun((1, 2, 3, 4))
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 4, in sun
    add_data += i
TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'

Obviously, Python cannot recognize this call method to calculate the result. Can I pass it one by one?

def sun(*arr):
    add_data = 0
    for i in arr:
        add_data += i
    return add_data

d = (1, 2, 3, 4)
a = sun(d[0], d[1], d[2], d[3])
print(a)

10

Facts have proved that this is possible. But new problems arise. If there are 1000 elements in a list or tuple. This is obviously unrealistic. So a new way to solve this problem.

def sun(*arr):
    add_data = 0
    for i in arr:
        add_data += i
    return add_data

d = (1, 2, 3, 4)
a = sun(*d)
print(a)

10

Not only did we get the desired results. And only need to add an "*" in front of the actual parameter i to solve the problem proudly. This is a common wording.

two. Named keyword parameters

Pass parameters for the keywords mentioned earlier. We set no restrictions when setting keyword parameters. That is, you want to set this parameter as a keyword pass parameter. Just set it as a keyword to pass parameters when calling, for example

def person(age, tall, city, name):
    person1 = {
        "name": name,
        "age": age,
        "tall": tall,
        "city": city
    }
    print(person1)
#  设置名字为关键字参数
person(23, 178, "成都", name="雯倾浅忆")

#  设置城市和名字为关键字参数
person(23, 178, city="成都", name="雯倾浅忆")

{'name': '雯倾浅忆', 'age': 23, 'tall': 178, 'city': '成都'}
{'name': '雯倾浅忆', 'age': 23, 'tall': 178, 'city': '成都'}

What if we want to check if age and tall are set as keyword parameters? Need to pass the kwcheck inside the function . Examples are as follows.

def person(age, name, **kw):
    if "tall" in kw and "city" in kw:
        person1 = {
            "name": name,
            "age": age,
        }
        print(person1)
#  设置名字为关键字参数
person(23, 178, tall=178, city="成都")

{'name': 178, 'age': 23}

Obviously, if any of tall and city are not keyword-passing parameters, the object will not be printed successfully.

def person(age, name, **kw):
    if "tall" in kw and "city" in kw:
        person1 = {
            "name": name,
            "age": age,
        }
        print(person1)
    else:
        print("参数不全  无法打印对象")
#  设置名字为关键字参数
person(23, 178, city="成都")

参数不全  无法打印对象

So the new question arises what is the formal parameter ** ke in the above code? Examples are as follows

def person(age, name, **kw):
    if "tall" in kw and "city" in kw:
        print(kw)
    else:
        print("参数不全  无法打印对象")
#  设置名字为关键字参数
person(23, 178, tall=178, city="成都")

{'tall': 178, 'city': '成都'}

It turns out that kw stands for a dictionary of named keywords. Knowing this, you can create the original dictionary about person1. Examples are as follows

def person(age, name, **kw):
    if "tall" in kw and "city" in kw:
        person1 = {
            "name": name,
            "age": age,
            "tall": kw['tall'],
            "city": kw['city']
        }
        print(person1)
    else:
        print("参数不全  无法打印对象")
#  设置名字为关键字参数
person(23, 178, tall=178, city="成都")

{'name': 178, 'age': 23, 'tall': 178, 'city': '成都'}

There is a new problem with the above wording. Is it possible for me to set extra keyword parameters?

def person( name, **kw):
    if "tall" in kw and "city" in kw:
        print(kw)
    else:
        print("参数不全  无法打印对象")
#  设置名字为关键字参数
person("小王", age=23, tall=178, city="成都")

{'age': 23, 'tall': 178, 'city': '成都'}

Obviously this is inconsistent with our willingness to only require the parameters of the keywords of tall and city, which means that the caller can still pass in unrestricted keyword parameters. At this time, if you want to limit the name of keyword parameters, you can use named keyword parameters, examples are as follows

def person(age, tall, *, city, name):
    person1 = {
        "name": name,
        "age": age,
        "tall": tall,
        "city": city
    }
    print(person1)

person(23, 178, city="成都", name="雯倾浅忆")

{'name': '雯倾浅忆', 'age': 23, 'tall': 178, 'city': '成都'}

The difference with ** ke is that named keyword parameters need to use "*" and subsequent parameters will be treated as named keyword parameters. If not set, an exception will be thrown

def person(age, tall, *, city, name):
    person1 = {
        "name": name,
        "age": age,
        "tall": tall,
        "city": city
    }
    print(person1)

person(23, 178, "成都", name="雯倾浅忆")

Traceback (most recent call last):
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 10, in <module>
    person(23, 178, "成都", name="雯倾浅忆")
TypeError: person() takes 2 positional arguments but 3 positional arguments (and 1 keyword-only argument) were given

If there is a variable parameter in the formal parameter. Then the following named keyword parameters do not need to be separated by symbols

def person(age, tall, *arr, city, name):
    person1 = {
        "name": name,
        "age": age,
        "tall": tall,
        "city": city,
    }
    print(person1)
    print(arr)

person(23, 178, [1, 2, 2], city="成都", name="雯倾浅忆")

{'name': '雯倾浅忆', 'age': 23, 'tall': 178, 'city': '成都'}
([1, 2, 2],)

In the presence of variable parameters. The parameters following it must be treated as named keyword parameters. Otherwise it will throw an exception

def person(age, tall, *arr, city, name):
    person1 = {
        "name": name,
        "age": age,
        "tall": tall,
        "city": city,
    }
    print(person1)
    print(arr)

person(23, 178, [1, 2, 2], "成都", "雯倾浅忆")

Traceback (most recent call last):
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 11, in <module>
    person(23, 178, [1, 2, 2], "成都", "雯倾浅忆")
TypeError: person() missing 2 required keyword-only arguments: 'city' and 'name'

Named keyword parameters can be set to default values ​​when calling without having to pass values

def person(age, tall, *, city="成都", name):
    person1 = {
        "name": name,
        "age": age,
        "tall": tall,
        "city": city
    }
    print(person1)

person(23, 178, name="雯倾浅忆")

{'name': '雯倾浅忆', 'age': 23, 'tall': 178, 'city': '成都'}

three. Parameter combination

To define a function in Python, you can use mandatory parameters (positional parameters), default parameters, variable parameters, keyword parameters, and named keyword parameters. These five parameters can be used in combination. But please note that the order of parameter definition must be: mandatory parameters (positional parameters), default parameters, variable parameters, named keyword parameters and keyword parameters.

Published 29 original articles · Like 133 · Visits 30,000+

Guess you like

Origin blog.csdn.net/qq_25502269/article/details/105692637