Multimethods in Python
Last Updated :
21 Apr, 2020
Multimethod basically means a function that has multiple versions, distinguished by the type of the arguments. For better understanding consider the below example.
@multimethod
def sum(x: int, y: int):
return x + y
@multimethod
def sum(x: str, y: str):
return x+" "+y
The above example is similar to
def sum(x, y):
if isinstance(x, int) and isinstance(y, int):
return x + y
elif isinstance(x, str) and isinstance(y, str):
return x + ' ' + y
Installation
At syntactical level, Python does not support multiple dispatch but it is possible to add multiple dispatch using a library extension multimethod
. To install this library type the below command in the terminal.
pip install multimethod
Example 1:
from multimethod import multimethod
@multimethod
def sum (x: int , y: int ):
return x + y
@multimethod
def sum (x: str , y: str ):
return x + " " + y
print ( sum ( 2 , 3 ))
print ( sum ( "Hello" , "World" ))
|
Output:
5
Hello World
Example 2:
from multimethod import multimethod
class GFG( object ):
@multimethod
def double( self , x: int ):
print ( 2 * x)
@multimethod
def double( self , x: complex ):
print ( "sorry, I don't like complex numbers" )
obj = GFG()
obj.double( 3 )
obj.double( 6j )
|
Output:
6
sorry, I don't like complex numbers
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...