python, * args and ** kwargs use

I. Introduction

1. * args and ** kwargs two variable parameter is a function

2. * args returns a Ganso

3. ** kwargs returns a dictionary

II. Demo

Definitions: For the following functions, * args can identify all the parameters other than non-A keyword parameter a = 1; ** kwargs only recognize this key parameter a = 1, the other is not identified

def add(*args, **kwargs):
    print(args, kwargs)


add(1, 2, 3, 4, a=1, b=2)
add(1)
add(a=1, b=2)
add(1, {"a": 1})
add("1", [1, 2], {"a": 1}, (1, 2))
add(*[1, 2], **{"a": 1})

result:

(1, 2, 3, 4) {'a': 1, 'b': 2}
(1,) {}
() {'a': 1, 'b': 2}
(1, {'a': 1}) {}
('1', [1, 2], {'a': 1}, (1, 2)) {}

(1, 2) {'a': 1}

in conclusion:

1. It is clear that only a = 1, b = 2 ** kwargs this is to recognize that, or else returns empty dictionary; for non-a = 1, b = 2 * args this is to recognize that, or else return an empty Ganso.

2. But for ({ "a": 1} * [1, 2], **) add this happen, why the result is (1, 2) { 'a': 1}, rather than ([1 , 2], { "a": 1}) it, it is because when you add a number * (1,2) * in front of it is equivalent to break it into two figures 1 and 2, and then passed a * args, and that for ** { "a": 1} * numbers with the addition of two equivalent so it is split into a = 1, and then passed ** kwargs, so the final result is (1 , 2) { 'a': 1}.

 

Guess you like

Origin www.cnblogs.com/hao2018/p/11537395.html