Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the parameter matching model in Python function

Shulou Source: shulou.com Published: 2022-06-03 00:09:07 09月19日 Update

Today, I will talk to you about what the parameter matching model in the Python function is. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Parameter matching model of Python function

Any parameter *

When our function receives any number of parameters, or cannot determine the number of parameters, we can use * to define any number of parameters. When this function is called, all its mismatched positional parameters are assigned to tuples. We can use loops or indexes in the function.

Def f (* args): # Direct print tuple parameter print (args) print ('-'* 20) # print tuple parameter [print (I) for i in args]... # pass one parameter f (1) print ('='* 20) # pass five parameters f (1, 2, 3, 4, 5)

Example result:

(1,)-1 = (1,2,3,4,5)-12345

# arbitrary parameters * *

And * * is used to collect keyword parameters and pass them to a new dictionary, that is, in the function, we can handle these parameters in the same way as dictionaries.

Def f (* * args): # directly print dictionary parameters print (args) for key, value in args.items (): print ('{}: {} '.format (key, value)) f (axi1) print (' ='* 20) f (axi1, bao2, cym3)

Example result:

{'averse: 1} a: 1 = {' averse: 1, 'baked: 2,' cached: 3} a: 1b: 2c: 3

Arbitrary parameter mixing

We can mix general parameters, * parameters, and * parameters to achieve more complex invocation methods.

Def f (a, * targs, * * dargs): print (a, targs, dargs) f

Example result:

1 (2,3) {"x": 1, "y": 2}

We can see that this kind of call is not so intuitive, and even some "confuse the public", so how can it be more intuitive in the function call when calling a complex arbitrary parameter?

Unpacking parameters

When we call a function, we can directly use * and * to pass parameters, and then let the function unpack automatically, which is similar to the previous sequence unpacking, which makes it more intuitive to use the call.

Def f (a, b, c, d): print (a, b, c, d) f (1, * (2, 3), * * {'dudes: 4})

Example result:

1234 after reading the above, do you have any further understanding of the parameter matching model in the Python function? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Parameters functions examples results models intuition content dictionaries ways complexity processing loops mixing confusion number location keys keywords sequences numbers Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Huawei OPPO Reno macOS vpn