0

I am new to python. But I know about method overloading. But I am confusion with overloading in python. Here my confusion code,

class OverLoad(object):
    """docstring for OverLoad"""
    def __init__(self, arg):
        super(OverLoad, self).__init__()
        self.arg = arg

    def adder(a, b):
        print a,b

    def adder(*a):
        print a

    def adder(a):

        print a
    def adder():

        print "no arg"

And please explain the above code.

codeimplementer
  • 3,303
  • 2
  • 14
  • 16
  • 1
    Python doesn't have method overloading - the last method you define is the one that's used... that could be why? :) Maybe have a look at: http://stackoverflow.com/questions/6434482/python-function-overloading – Jon Clements Dec 05 '13 at 08:36
  • Thanks @Jon. you have provided link so helpful to me. – codeimplementer Dec 05 '13 at 08:52

2 Answers2

1

Python-style overloading:

def adder(self, *arg, **kwd):

you can call:

some_class.adder(1, 2)
some_class.adder(1, 2, 3, 4, 5, 6, 7, 9, 10 ....)
some_class.adder(1, 2, 3, 4, arg1=5, arg2=6, arg3=7)
some_class.adder(arg1=1, arg2=2, arg3=3)

but most likely your variant:

def adder(self, *arg):
    if len(arg) == 0:
       print "no arg"
    return sum(arg)

and call:

some_class.adder(1,2,3,4,5,7,8,9,10)
sheh
  • 1,003
  • 1
  • 9
  • 31
0

Python does not support method overloading.

Refer to this doc. When you define a method in a class, Python creates a function object first and then binds the function object and the function name that you defines. So in your code example, only the last adder() function takes effect.

flyer
  • 9,280
  • 11
  • 46
  • 62