Chapter VII, the basis of the function of the variable length parameter 07

Chapter VII, the basis of the function of the variable-length argument

A variable length parameter of *

* Parameter will overflow in the position-all argument, and then stored tuple, the tuple is then assigned to the parameters *

Note : * args parameter called convention

def sum_self(*args):
    res = 0
    for num in args:
        res += num
    return res


res = sum_self(1, 2, 3, 4)
print(res)

Second, the variable-length argument *

The arguments * * * the value of the loop will be removed, broken into position argument. * After the encounter with the argument, it is the position of the argument, it should be immediately broken up into position to see the argument

def func(x, y, z, *args):
    print(x, y, z, args)


func(1, *(1, 2), 3, 4)

1 1 2 (3, 4)

Third, the variable length parameter **

** The parameter will overflow all arguments received keyword, and store the dictionary form, then the parameters assigned to the dictionary **

Note : The parameter is the name of the convention ** ** kwargs

def func(**kwargw):
    print(kwargw)


func(a=5)

{'a': 5}

Fourth, the variable-length argument **

The argument **, ** value parameter extraction cycle, broken into Keyword argument. After the encounter with the argument **, it is the key argument, it should be immediately broken into keyword arguments to see

def func(x, y, z, **kwargs):
    print(x, y, z, kwargs)


func(1, 3, 4, **{'a': 1, 'b': 2})

1 3 4 {'a': 1, 'b': 2}

Fifth, the variable-length parameters are applied

def index(name, age, sex):
    print(f"name: {name}, age: {age}, sex: {sex}")


def wrapper(*args, **kwargs):
    print(f"args: {args}")
    print(f"kwargs: {kwargs}")
    index(*args, **kwargs)


wrapper(name='nick', sex='male', age=19)
args: ()
kwargs: {'name': 'nick', 'sex': 'male', 'age': 19}
name: nick, age: 19, sex: male

Six key parameter named

User function must pass parameters by keyword real

def register(x, y, **kwargs):
    if 'name' not in kwargs or 'age' not in kwargs:
        print('用户名和年龄必须使用关键字的形式传值')
        return
    print(kwargs['name'])
    print(kwargs['age'])


register(1, 2, name='nick', age=19)
nick
19

Name Keyword parameter: function definition stage, parameters are named after the * key parameters

Features : In the pass by value, key = value must be in accordance with the manner and key must be named keyword arguments specified parameter name

def register(x, y, *, name, gender='male', age):
    print(x)
    print(age)


register(1, 2, x='nick', age=19)  # TypeError: register() got multiple values for argument 'x'

** The name parameter x into the specified parameter name like

Guess you like

Origin www.cnblogs.com/demiao/p/11335175.html