Packaging and unpacking of * and * * in Python

Source: Internet
Author: User
Tags function definition unpack

The * and * * In Python allow the function to support any number of arguments, which have different purposes in function definition and invocation.

I. Packing parameters* Function: In the function definition, collect all positional parameters into a new tuple and assign the tuple to the variable args
def F (*args):    print(args)    >>> F () ()>>> F (1 ) (1,)>>> F (1, 2, 3, 4) (1, 2, 3, 4)
* * Role: In the function definition, the Collection keyword argument is passed to a dictionary and the dictionary is assigned to the variable Kwargs
def F (* *Kwargs)    :print(Kwargs    )>>> f () {}>> > f (a=1, b=2) {'a'b': 2}
two. Unpacking Parameters* Function: * Ability to unpack tuples or lists into different parameters in a functional call
def func (A, B, C, D):     Print (A, B, C, D)     >>> args = (1, 2, 3, 4)>>> func (*args)1 2 3 4>>> args = [1, 2, 3, 4] >>> func (*args)1 2 3 4
* * Function: In a function call, * * will unpack a dictionary as a key/value, making it a separate keyword parameter
def func (A, B, C, D):     Print (A, B, C, D)     >>> Kwargs = {"a""b""C " " " D ": 4}>>> func (* *Kwargs)1 2 3 4
three. Note1. When the function is defined, * means packing, inside the function body, * still means unpacking (print (*args) is actually called the print function)
>>>defFoo (*args, * *Kwargs):Print(args)#Unpacked Parameters    Print(*args)#Unpacking Parameters>>> v = (1, 2, 4)>>> d = {'a': 1,'b': 12}>>>foo (V, D) ((1, 2, 4), {'a': 1,'b': 12})(1, 2, 4) {'a': 1,'b': 12}
2. Packaging and unpacking can not be separated from the function of the existence

On the surface, there is no function, in fact there is a function call of format

>>> C = {"name"'Zhang'"Age" : 2}>>> * *csyntaxerror:invalid syntax"name:{name}, Age:{age}  ". Format (* *c)'name:zhang, age:2'

Definition of the Format function in the reference source

But this dictionary unpacking cannot be output with the print function

Print (* *c) Traceback (most recent):   " <pyshell#40> "  in <module>    print(**"Age"is   for this function

Because this is the way the dictionary is solved:

**c = name='Zhang', age=2

The print function supports only *args and does not support **kwargs

3. Application in DDT

@ddt. Data (*all_casedatas), data is a function that invokes a function when the parameter *all_casedatas automatically switches the argument list [{}, {}, {} ...] Unpack {},{},{} ..., in the DEF data (*values) function, * automatically packages each positional parameter into a new tuple ({}, {}, {} ...), then @ddt.data can get each piece of data as a test case

@ddt. Data (*All_casedatas)deftest_my_request (Self, case_data):GlobalGlobal_varifLen (global_var)! = 0 andcase_data["Request_data"] is  notNone: forKey, ValueinchGlobal_var.items ():ifcase_data["Request_data"].find (key)! =-1: case_data["Request_data"] = case_data["Request_data"].replace (key, value)
Four. Practice

Please write out the results of the following code

defF (str1, *args, * *Kwargs):Print(str1, args, Kwargs) L= [1, 2, 3]t= [4, 5, 6]d= {"a": 7,"b": 8,"C": 9}f (1, 2) F (1, 2, 3,"python") F ("python", A=1, b=2, c=3)Print("================") F ("python", L, D) F ("python", *t) F ("python", *l, * *d) F ("python", q="winning", **d) Operation Result:1 (2,) {}1 (2, 3,'python') {}python () {'a': 1,'b': 2,'C': 3}================python ([1, 2, 3], {'a': 7,'b': 8,'C'8 {}) {}python (4, 5, 6) {}python (1, 2, 3) {'a': 7,'b': 8,'C'8 {}python () {'a': 7,'b': 8,'Q':'winning','C': 9}

It is important to note that f ("Python", *t) is to unpack the list T first into 4, 5, 6, and then in def f (str1, *args, **kwargs): RePack 4, 5, 6 into a new tuple (4, 5, 6) and pass it to the variable args

Packaging and unpacking of * and * * in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.