Python function Dynamic parameter detailed

Source: Internet
Author: User

Dynamic parameters for Python:

1, the parameter before a "*": in the function will be transferred to a tuple of parameters.

    

Func (* func (123,1,2,) result: (123, 1, 2, ' a ')

2, "**args" parameter: The function is turned into a dictionary.

    

If this is the case, there will be an error because no key or value:def func (**args) is specified: print (args) func (123,1,2, ' a ') result:TypeError:func () takes 0 Positional arguments but 4 were givendef func (**args): print (args) func (a=1,b=2) result:{' a ': 1, ' b ': 2}

3, the situation of mixed dynamic parameters:

def func (*args,**kwargs): print ("%s----%s"% (args,kwargs)) func (1,2,a=1,b=2) Result: (1, 2)----{' b ': 2, ' A ': 1} it's no problem, you need Note that the *args must be in the front **kwargs, and the parameters are the Same.

4, variables when dynamic parameters are in the Case:

 

In this case, if we directly upload a list to the front, a dict to the Back: def func (*args,**kwargs): print ("%s----%s"% (args,kwargs)) list=[1,2]dic={' a ': 1, ' b ': 2}func (list,dic) Result: ([1, 2], {' b ': 2, ' A ': 1})----the dictionary after {} is empty--! so, we need to call the function to know that the variable is the parameter of *args, which is the parameter of the **args, the correct argument is written: func (*list,**dicresult: (1, 2)----{' a ': 1, ' b ': 2}

  

    

This article from "Lu Yaliang" blog, reproduced please contact the author!

Python function Dynamic parameter detailed

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.