Variable-length arguments to functions

# *args: positional arguments, collected as tuples
def func1(*args):
    print(args)
    for i in args:
        print(i)

func1('python', 28, 'man', 'meiguo')

# **kwargs : collect keyword arguments, merge dictionaries
def func2(**kwargs):
    print(kwargs)
    for key, value in kwargs.items():
        print(key)
        print(value)

func2(name='python', age=28, sex='man', weizhi='helan')


def fun(a, b, *args, **kwargs):
    """Variable parameter demonstration example"""
    print("a =%d" % a)
    print("b =%d" % b)
    print("args:")
    print(args)
    print("kwargs: ")
    for key, value in kwargs.items():
        print("value=%s" % value)

print("-fu-"*10)
c = (3, 4, 5)
d = {"m": 6, "n": 7, "p": 8} # When passing in tuples and dictionaries, you should add *, if not, it will be treated as a normal variable-length parameter
fun(1, 2, *c, **d) # Even if the variable length parameter is also a tuple, it will become the first position of the variable length parameter in the tuple given to the actual parameter
fun(1, 2, c, d) # Make a tuple and add a comma ((),) like this. , dictionary, must be double *
                    # So in the future, you must remember the * sign when passing tuples and dictionaries to indefinite long parameters
# Default arguments are after *args
print('-fun-'*10)
def sum_nums_3(a, *args, b=22, c=33, **kwargs):
    print(a)
    print(b)
    print(c)
    print(args)
    print(kwargs)

sum_nums_3(100, 200, 300, 400, 500, 600, 700, b=1, c=2, mm=800, nn=900)
# If many values ​​are variable length parameters, then in this case, you can put the default parameters after *args
# But if there are **kwargs, **kwargs must be last
# The variable args with an asterisk (*) will store all unnamed variable parameters, args is a tuple
# The variable kwargs with ** will store named parameters, that is, parameters in the form of key=value, and kwargs is a dictionary

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325847285&siteId=291194637