0
Args and Kwargs in Python?
I have watched lots of Python tutorials and the keywords "args" and "kwargs" are used often but I'm unsure of their use? Can anyone comment what they are and how they can be used? Note: I haven't finished the Python course completely so they may be in the course but I have not learned about them yet! Thanks! :)
3 Antworten
+ 6
*args is used when you're not sure how many arguments will be passed to your function.
>>> def f(arg1, *args):
print(arg1)
print(args)
>>> f(1,2,3,4,5,6)
1
(2, 3, 4, 5, 6)
So if you have a required argument arg1, the first argument you pass to the function will be arg1, and the rest (no matter how many) will be a part of a tuple *args, which can be unpacked inside the function and used as needed.
Kwargs is a dictionary of keyword arguments that is passed to the function as a dictionary:
>>> def f(arg1, *args, **kwargs):
print(arg1)
print(args)
print(kwargs)
>>> f(1,2,3,4,5,6, keyword_arg_1 = 1, keyword_arg_2 = 2)
1
(2, 3, 4, 5, 6)
{'keyword_arg_1': 1, 'keyword_arg_2': 2}
Hope this clears it up (:
+ 1
Thanks that's really helpful! 😃
+ 1
Here is my primer on *args in Python - hope you find it useful!
https://code.sololearn.com/cce88fWlK7L7/?ref=app