Is it possible to overload __init__ method based on argument type?

Submitted 3 years, 7 months ago
Ticket #427
Views 472
Language/Framework Python
Priority Medium
Status Closed

If possible how can we do it?

In c++ it is quite easy ,but I cant get it on python..

Any help will be appreciatable....

Submitted on May 01, 21
add a comment

1 Answer

Verified

Python does not support method overloading by default

Maybe you can try with multipledispatch. I don't know if it will work with __init__()

# FIRST INSTALL THE PACKAGE
# pip3 install multipledispatch

from multipledispatch import dispatch
  
#passing one parameter
@dispatch(int,int)
def product(first,second):
    result = first*second
    print(result);
  
#passing two parameters
@dispatch(int,int,int)
def product(first,second,third):
    result  = first * second * third
    print(result);
  
#you can also pass data type of any value as per requirement
@dispatch(float,float,float)
def product(first,second,third):
    result  = first * second * third
    print(result);
  
  
#calling product method with 2 arguments
product(2,3,2) #this will give output of 12
product(2.2,3.4,2.3) # this will give output of 17.985999999999997

Source: geeks_for_geeks (https://www.geeksforgeeks.org/python-method-overloading/)

Submitted 3 years, 7 months ago


Latest Blogs