Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How can we overload a Python function?

I have the following code for a python function.

class Human:
      def sayHello():
          if name is not None:
             print 'Hello ' + name
          else:
             print 'Hello '

 How can I overload this python function?


1 Answer
Rajendra Dharmkar

In Python you can define a method in such a way that there are multiple ways to call it. Depending on the function definition, it can be called with zero, one, two or more parameters. This is known as method overloading.

In the given code, there is a class with one method sayHello(). We rewrite as shown below. 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. To implement method overloading, we call the method sayHello() in two ways: 1. obj.sayHello() and 2.obj.sayHello('Rambo')

We created a method that can be called with fewer arguments than it is defined to allow. We are not limited to two variables, given method can have more variables which are optional.

class Human:
      def sayHello(self, name=None):
          if name is not None:
             print 'Hello ' + name
          else:
             print 'Hello '
obj = Human()
print(obj.sayHello())
print(obj.sayHello('Rambo'))

OUTPUT

Hello
None
Hello Rambo
None
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.