Friday, March 5, 2010

What the Heck is *args and **kwargs in my Function?

Take the following code example:


Let's call this function:
c = Child()
c.Method1()
c.method2()
c.method3()
 
You'll notice that method3() will not be called because our super() is passing in a variable gp, and it is expecting all classes to accept one parameter in the __init__(). 
 
A small change to your program can be done to fix this problem by using *args and **kwargs.
The *args is used to pass a variable-length argument list, and the **kwargs form is used to pass a dictionary object of variable length.
 
By modifying the class SomeClass' __init__() by adding *args and **kwargs, you can now have functions that doesn't need variables to just ignore the variables being passed for this function.

In the other Classes you should use either the *args or **kwargs for your parameters too.  You can check if the len() of the list is correct, and if so, assign the values.