0

I wanted to use overloading in Iron Python but seems it's not working :

import sys
import clr

def  af(a, b):
     c = a+b
     print c
     return c
def af(j):
  y = j*j
  print y
  return y

 af(6,7)
 af(5)

I get a error =\ Is there any way to use overloading ? my purpose is to write a function : foo(doAction,numTimes) when by default if I use foo(action): it will do it once, or I'll write : foo(action,6)

thanks a lot!!!

user1386966
  • 3,302
  • 13
  • 43
  • 72
  • possible duplicate of [Function overloading in Python: Missing](http://stackoverflow.com/questions/733264/function-overloading-in-python-missing) – Tymoteusz Paul Oct 09 '13 at 08:46
  • This might help you: http://stackoverflow.com/questions/7113032/overloaded-functions-in-python – jowa Oct 09 '13 at 08:48

1 Answers1

1

IronPython might run on the CLR but that doesn't make it C#. In any kind of Python, you can only define a function once. Defining a function is really just assigning to a name, so in your code you assign a function to af, then assign another one to the same name, so the first one is simply discarded.

The way to do this in Python is via default arguments:

def aj(a, b=None):
    if b is not None:
        result = a + b
    else:
        result = a * a
    print result
    return result

For your actual use case of course you can define numtimes with a default of 1:

def foo(action, numtimes=1):
    # whatever
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895