[Tutor] Method overloading in Python
Manprit Singh
manpritsinghece at gmail.com
Thu Nov 4 08:39:07 EDT 2021
Dear sir,
Although Method overloading can't be truly achieved in Python , But a
similar effect can be made to happen - like if a method or __init__ () can
behave differently in case of different types of inputs.
I have written an example below to show it :
In this example i have made a class Awards, My purpose of this class is to
get the name of award based on category
for category "A" or 1 award is "TV"
for category "B" or 2 award is "AC"
for category "C" or 3 award is "Fridge"
The program allows user to give input of category either in string from or
in integer from, means the program must give result as "TV" when the
category is either A or 1
class Awards:
cat1 = {"A": "TV", "B": "AC", "C": "Fridge"}
cat2 = {1: "TV", 2: "AC", 3: "Fridge"}
def __init__(self, cat=None):
if isinstance(cat, str):
self.award = self.cat1[cat]
elif isinstance(cat, int):
self.award = self.cat2[cat]
def showaward(self):
return self.award
prize = Awards(1)
print(prize.showaward()) # prints "TV which is right answer for
category 1
prize = Awards("A") # prints "TV which is right answer for
category "A
print(prize.showaward())
Here I have overloaded the __init__() , as it is behaving differently in
case of integer input and differently in case of string input. It will
assign "TV" to self.award if the object creation is done either with 1 or
"A" as argument passed during class instantiation. Is my thinking correct
?
My second question is if a class can have more than one class variable,
here I have put 2 class variables in the class cat1 and cat2 . Kindly
comment .
Kindly address any other shortcoming too .
Regards
Manprit Singh
More information about the Tutor
mailing list