+ 1

what is the my_func() doing?

def my_func(x, y=7, *args, **kwargs): print(kwargs) my_func(2, 3, 4, 5, 6, a=7, b=8) What is the line of code above doing?

7th Aug 2019, 2:26 AM
LP13
LP13 - avatar
2 Respuestas
+ 5
For *args, the single asterisk prior to the identifier allows us to store and pass around a number of arguments. def func(*args): print(args) func(1,2,3) #prints (1, 2, 3) **kwargs on the other hand allows us to store and pass around a keyworded argument list. def func(**kwargs): print(kwargs) func(a=1,b=2,c=3) #prints {'a': 1, 'b': 2, 'c': 3} In your case, def my_func(x, y=7, *args, **kwargs): print(kwargs) my_func(2, 3, 4, 5, 6, a=7, b=8) would print {'a' : 7, 'b' : 8} since 2 and 3 is assigned to parameters x and y, and 4,5,6 goes to *args.
7th Aug 2019, 2:41 AM
Fermi
Fermi - avatar
+ 3
The line above is calling the function "my_func()" with several parameters. Since the function only wants the kwargs variable to print, unpacking the two variables as a dictionary kwargs={'a':7, 'b':8} is what this function is doing
7th Aug 2019, 2:49 AM
Steven M
Steven M - avatar