- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we overload a Python function?
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'))
Hello None Hello Rambo None
- Can we overload Java main method?
- Can we overload the main method in Java?
- Can we overload or override a static method in Java?
- How can we define a Python function at runtime?
- Can we overload methods of an interface in Java?
- Can we Overload or Override static methods in Java?
- How can we return a dictionary from a Python function?
- How can we return a tuple from a Python function?
- How can we return a list from a Python function?
- How we can call Python function from MATLAB?
- Can we explicitly define datatype in a Python Function?
- How can we alter a MySQL stored function?
- How can a Python function return a function?
- How to overload python ternary operator?
- How to overload Python comparison operators?