0

In python I cannot seem to overload the below functions:

#!/usr/bin/env python

import subprocess
def my_function (a) :
    subprocess.call(['proc', a])
    return;

def my_function (a, b) :
    subprocess.call(['proc','-i',a,b])
    return;

def my_function (a, b, c, d) :
    subprocess.call(['proc','-i',a,b,'-u',c,d])
    return; 

E.g. when I call with:

mymodules.my_function("a", "b")

I get:

Traceback (most recent call last):
  File "sample.py", line 11, in <module>
    mymodules.my_function("a", "b") 
TypeError: my_function() takes exactly 4 arguments (2 given)

Why does it try to call the function taking 4 arguments?

u123
  • 15,603
  • 58
  • 186
  • 303

1 Answers1

5

Because overloading of function does not work in python as it does in other languages.

What I would do :

def my_function (a, b=None, c=None, d=None) :
    if b is None:
        subprocess.call(['proc', a])
    elif c is None:
        subprocess.call(['proc','-i',a,b])
    else:
        subprocess.call(['proc','-i',a,b,'-u',c,d])
    return; 

It will automatically detect the variables that you enter, and fill the ones you don't enter with None by default. Of course for it to work, your variables must never take the value of None

WNG
  • 3,705
  • 2
  • 22
  • 31