Functions, Operators, and Overloading?

Terry Reedy tjreedy at udel.edu
Mon Jul 24 13:55:13 EDT 2006


"Michael Yanowitz" <m.yanowitz at kearfott.com> wrote in message 
news:HGEOKIAPAMCIFPPBDALKAEBACBAA.m.yanowitz at kearfott.com...
> Hello:
>
>   Maybe I am missing something, but from what I've seen,
> it is not possible to overload functions in Python. That
> is I can't have a
>  def func1 (int1, string1):
>   and a
>  def func1 (int1, int3, string1, string2):
>    without the second func1 overwriting the first.

I am hard put to think of why you would want to do something like that in 
real code.  The 2nd-parameter type mismatch will make using code harder to 
write and read without bugs.  Why not just give the two 
different-but-related functions two different-but-related, names?  But if 
you insist ..., here is the Python way...

def func1(int1, int3, string1=None, string2=None):
  "doc short calling sequence"
  if string1==None:
    string1 = int3; del int3, string2
    <proceed with first body>
  else:
    <proceed with second body>

or
def func1(int1, *args):
  if len(args ==1):
    string1 = args[0]; del args
    <proceed with first body>
  elif len(args ==3):
    int3,string1,string2 = args; del args
    <proceed with second body>
  else: <raise error>

>   However, operators can be overloaded.

In the sense that you can define classes with appropriate special methods. 
You can also give two different classes methods named 'func1'.

>   So can I define a new operator?

No.

Terry Jan Reedy






More information about the Python-list mailing list