Method overloading in python with no default parameters

Since methods are evaluated at declaration time and not at run time the default values for method parameters cannot be dynamically set at declaration. Which means we cannot overload a function call like we can do in C++ such as this

int func()
int func(int c)

However, the workaround is to set the argument parameters to None, which allows the method to be called without any arguments. For example, the method

  def getdata(self, startdate, enddate):

when called as

s = obj.getdata()

Will raise an exception

TypeError: getdata() missing 2 required positional arguments: ‘startdate’ and ‘enddate’

We need to modify the declaration to

  def getdata(self, startdate=None, enddate=None):
       if startdate is None:
           startdate = self.stockdata.index[0]
       if enddate is None:
           enddate = self.stockdata.index[-1]

That will define the method as taking one, two, or no arguments. When called without arguments the if statements will inject the parameters dynamically during runtime.

Reference:
Using self.xxxx as a default parameter in a class method

 

Leave a comment