Method overloading


method overloading
Several ways to call a method (method overloading)

In Python you can define a method in such a way that there are multiple ways to call it.

Given a single method or function, we can specify the number of parameters ourself.

Depending on the function definition, it can be called with zero, one, two or more parameters.

This is known as method overloading. Not all programming languages support method overloading, but Python does.

Related course
Python: Object Oriented Programming

Method overloading example

We create a class with one method sayHello(). The first parameter of this method is set to None, this gives us the option to call it with or without a parameter.

An object is created based on the class, and we call its method using zero and one parameter.

#!/usr/bin/env python
 
class Human:
 
def sayHello(self, name=None):
 
if name is not None:
print 'Hello ' + name
else:
print 'Hello '
 
# Create instance
obj = Human()
 
# Call the method
obj.sayHello()
 
# Call the method with a parameter
obj.sayHello('Guido')

Output:

Hello
Hello Guido

To clarify method overloading, we can now call the method sayHello() in two ways:

obj.sayHello()
obj.sayHello('Guido')

We created a method that can be called with fewer arguments than it is defined to allow.

We are not limited to two variables, your method could have more variables which are optional.

Back
Next

18 thoughts on “Method overloading

  1. Michael 'Flip' McFadden - March 7, 2018

    I, personally, wouldn’t shorten that line.

    Reason 1: “Explicit is better than Implicit”
    “None” having a Truth value of “False” is something I don’t like relying on.

    Reason 2: There may be a valid names that have truth values of False. In this case, the output is not immediately obvious:

      obj.sayHello(0)    #'Hello 0'  or 'Hello'
     
      class HackShortenedForm(str):
              def __nonzero___(self):
                   return False
     
     
    name = HackShortenedForm("Guido")
    print name  #Guido
    print "Hello" + name   #Hello Guido
    obj.sayHello(name):    #Hello

    Since you can’t type check within the function definition, it’s best to type check the default parameter of None. This is best practice for any loosely typed language. Don’t cast it to a bool and expect it to behave properly.

    1. Frank - March 11, 2018

      Thanks!

Leave a Reply