Overloading in Python


Some say Python doesn’t allow overloading of methods or constructors. Well, they are right in some way!  A coding example below,

def add(a,b):
    return a+b

def add(a,b,c):
    return a+b+c

print add(4,5)

If you try to run the above piece of code, you get an error stating, “TypeError: add() takes exactly 3 arguments (2 given)”. This is because, Python understands the latest definition of method add() which takes only two arguments. Even though a method add() that takes care of three arguments exists, it didn’t get called. Hence you would be safe to say, overloading methods in Python is not supported.

But, then there are folks who are more than willing to say, ‘Oh! Python supports all!’ Yes, Python supports overloading but in a Pythonic way. Here’s an example,

def add(instanceOf, *args):
    if instanceOf == 'int':
        result = 0
    if instanceOf == 'str':
        result = ''
    for i in args:
        result = result + i
    return result

print add('int', 3,4,5)
print add('str', 'I',' am',' in', ' Python')

Output:
12
I am in Python

In the above code snippet, two things are achieved:

-          Irrespective of the different number of arguments, method add() works well

-          Also, based on the data type of input, data  type of output is changed

So, overloading IS there in Python!! :)

About these ads

About Chetan Giridhar

An avid technologist, blogger and a newbie photographer.

Posted on April 10, 2012, in Python and tagged , , , , , , , , , . Bookmark the permalink. 3 Comments.

  1. It looks very similar to variable argument functions e.g “printf” of C :)

  2. I would use following syntax:
    def add(a,b,c=0):
    return a+b+c
    Now add(5,5) works just fine.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: