In this python oops program, we will create a class with method overloading in Python. The program showcases method overloading in Python.
Class with method overloading
Steps to solve the program
- The MyClass class has a method called method that takes two parameters: param1 and param2. The param2 parameter is set to None by default.
- Inside the method, there is an if statement that checks if param2 is None. If it is None, it means that only one parameter (param1) was passed, and it prints “Single parameter: ” followed by the value of param1. If param2 is not None, it means that both parameters (param1 and param2) were passed, and it prints “Two parameters: ” followed by the values of param1 and param2.
- An object obj of the MyClass class is created.
- The obj.method(“Hello”) call invokes the method of the MyClass object with a single argument. Since param2 is not provided, the if condition in the method evaluates to True, and it prints “Single parameter: Hello”.
- The obj.method(“Hello”, “World”) call invokes the method of the MyClass object with two arguments. The if condition in the method evaluates to False since param2 is provided. It prints “Two parameters: Hello World”.
class MyClass:
def method(self, param1, param2=None):
if param2 is None:
print("Single parameter:", param1)
else:
print("Two parameters:", param1, param2)
# Create an object of the class
obj = MyClass()
# Call the method with different number of arguments
obj.method("Hello")
obj.method("Hello", "World")
Output:
Single parameter: Hello
Two parameters: Hello World
Related Articles
Python Class with Method Overriding.
Write a Python Class Program with an Abstract method.
Write a Python Class program to create a class with data hiding.
Python Class Structure for School Management System.
Write a Python Class Structure for Employee Management Application.
Write a Python Class with @property decorator.