13. Python's way of method overloading

Overloading is the ability of a function (method) to behave in different ways based on the parameters that are passed to the function (method).

Definition: Method overloading means the ability to have multiple methods with same name which vary in their parameters. It is one of the concepts in Polymorphism. But Python does not allow this kind of overloading i.e., multiple methods with same name is not possible.

In Python, we can create a method that can be called in different ways. In a single method, we specify the total number of parameters and depending on the method definition, we can call it with zero, one or more arguments. The body of the method contains the logic of what needs to be done in case any parameter of the method is absent.This process of calling the same method in different ways is called method overloading.

This kind of method overloading is not supported by many OOP languages, but Python allows it.

An overloaded method is defined as:

class Class_Name:
	def method1(self, name = None, wish = None):
		#body of the method
		statement 1
		...
		statement n
object_1 = Class_Name()
object_1.method1() # Calling method1 with zero parameters
object_1.method1("Ram") # Calling method1 with only one parameter
object_1.method1("Ram","Good Morning") # Calling method1 with two parameters

This means the same method can be called using zero, one or two arguments. The body of method1 contains the logic (code) of what needs to be done.

Understand the below code:

class Greeting:
  def sayHello(selfname = Nonewish = None):
    if name is not None and wish is not None:
      print ('Hello' + name + wish)
    elif name is not None and wish is None:
      print ('Hello' + name)
    else:
      print ('Hello')
greet = Greeting()
# Call the method with zero, one and two parameters
greet.sayHello()
greet.sayHello('Ram')
greet.sayHello('Ram,', 'Good Morning!!!')
Expected Output:
Hello
HelloRam
HelloRam,Good Morning!!!