+ 1

*args and *kwargs

Please if someone can tell me for what is used *args and for what *kwargs in Python. I'm confused. ...Sorry for my bad English...

18th Feb 2019, 10:50 AM
Baltazarus
Baltazarus - avatar
4 odpowiedzi
+ 7
Parameters without * are standard parameters. They need to be provided when the function is called. Parameters with * are optional parameters. They can be omitted. If you provide them, they will be stored in a tuple. Parameters with ** are keyword parameters. They can be omitted. If you provide them, they will be stored in a dictionary. Example: def func(a, b, *c, **d): print(a) print(b) print(c) print(d) func() expects at least two arguments, a and b. If you provide more arguments, they will be stored in the tuple c, keyword arguments in the dict d. func(1) # error: func() expects at least two arguments (a and b) func(1, 2) # output: 1, 2, (), {} <= no optional argument c (empty tuple), no keyword argument (empty dict) func(1, 2, 3) # 1, 2, (3, ), {} <= optional argument c is stored in a tuple, no keyword arguments (empty dict) func(1, 2, 3, 4, 5, 6, 7) # 1, 2, (3, 4, 5, 6, 7), {} <= 3-7 are all optional arguments, all stored in a tuple, no keyword arguments (empty dict) func(1, 2, 3, 4, k=9, m=10) # a = 1, b = 2, c = (3, 4), d = {'k': 9, 'm': 10}
18th Feb 2019, 1:18 PM
Anna
Anna - avatar
18th Feb 2019, 11:04 AM
Hubert Dudek
Hubert Dudek - avatar
+ 2
Anna thanks so much 😊
18th Feb 2019, 1:26 PM
Baltazarus
Baltazarus - avatar
0
18th Feb 2019, 1:27 PM
Baltazarus
Baltazarus - avatar