optional arguments in initializer of python class

I am too new to stackoverflow to up-vote or comment, but I approve of ronak's answer. Gareth Latty's comment about default parameters is addressed by using the [default] option of the get method.

dictionary.get(key[, default])

using **args allows for less/ more readable code when there are many optional variables to be passed. It is simply passing passing dictionary key-value pairs as parameters.


You can set default parameters:

class OpticalTransition(object):
    def __init__(self, chemical, i, j=None, k=0):
        self.chemical = chemical
        self.i = i
        self.k = k
        self.j = j if j is not None else i

If you don't explicitly call the class with j and k, your instance will use the defaults you defined in the init parameters. So when you create an instance of this object, you can use all four parameters as normal: OpticalTransition('sodium', 5, 100, 27)

Or you can omit the parameters with defaults with OpticalTransition('sodium', 5), which would be interpreted as OpticalTransition('sodium', 5, None, 0)

You can use some default values but not all of them as well, by referencing the name of the parameter: OpticalTransition('sodium', 5, k=27) uses j's default but not k's.

Python won't allow you to do j=i as a default parameter (i isn't an existing object that the class definition can see), so the self.j line handles this with an if statement that in effect does the same thing.

Tags:

Python

Oop

Object