Python3 special function parameter is used: *, * args, ** kwargs

Python3 special function parameter is used: *, * args, ** kwargs

== Usage 1: variable length parameter ==

When an unspecified number of function parameters need, you can use * args and ** kwargs,

All location parameters are stored in the * args, stored in the form of tuples, directly args, when the band does not need to call *

All key parameters are saved in the ** kwargs, save in the form of a dictionary, but also directly use when calling kwargs

#demo1:
def func(*args, **kwargs):
    print(args)
    print(kwargs)

func("jack", 18, "male")
#output:
('jack', 18, 'male')
{}

The key parameter is not used when calling, so kwargs the dictionary is empty

#demo2:
def func(*args, **kwargs):
    print(args)
    print(kwargs)

func(name="jack", age=18, sex="male")
#output:
()
{'name': 'jack', 'age': 18, 'sex': 'male'}

Not used when calling positional parameters, so it was empty tuple args, and keyword names used do not appear in the parameter list in the function definition

#demo3:
def func(*args, **kwargs):
    print(args)
    print(kwargs)

func("jack", 18, sex="male")
# func(name="jack", 18,"male") 调用时报错
#output:
('jack', 18)
{'sex': 'male'}

Tune while using positional parameters and key parameters of the key parameters to be placed in the position parameter, otherwise it will error

== Note: ==

  • * Args and ** kwargs inside the args parameter name, kwargs can be any variable name, args with convention and kwargs

== Usage 2: When parameter called the * and * para must be a key parameter ==

#demo1:
def func(x, *, y):
    print(x, y)

func(3, y=5)
func(x=3, y=5)
# func(x=3, 5)  报错
# func(3, 5)    报错
#output:
3 5
3 5
  • * After the call parameters must be a critical parameter * before does not limit,

  • * If the first, then the back of the parameter in the parameter list of key parameters must be used

#demo2:
def func(x, *para, y):
    print(x, para, y)

func(3, 4, y=5)
#output:
3 (4,) 5

Guess you like

Origin www.cnblogs.com/liuxu2019/p/11343924.html