# How can we overload a Python function?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

## Example

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
Updated on 13-Feb-2020 06:03:08