*args, **kwargs - AndrewMZ6/python_cheat_sheet GitHub Wiki
Let's create a class using *args
and **kwargs
and see what are they exactly
class myclass:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
a = myclass()
print(a.args, type(a.args))
print(a.kwargs, type(a.kwargs))
output:
() <class 'tuple'>
{} <class 'dict'>
Pass some arguments to constructor
b = myclass(1, 2, 3, key1 = 'value1', key2 = 'value2')
print(b.args, type(b.args))
print(b.kwargs, type(b.kwargs))
output:
(1, 2, 3) <class 'tuple'>
{'key1': 'value1', 'key2': 'value2'} <class 'dict'>
A variable preceded with *
can unpack some collection
a, b, *c = (1, 2, 3, 4, 5, 6)
print(a)
print(b)
print(c, type(c))
output:
1
2
[3, 4, 5, 6] <class 'list'>