Tag: method overloading
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 Programming Bootcamp: Go from zero to hero
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 |
Output:
Hello |
To clarify method overloading, we can now call the method sayHello() in two ways:
obj.sayHello() |
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.
If you are new to Python programming, I highly recommend this book.