[Tutor] Method overloading in Python
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Nov 4 11:39:46 EDT 2021
On 04/11/2021 12:39, Manprit Singh wrote:
> 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 :
While it is possible to do that, it's usually a bad code smell.
I'd question whether you might be better defining a few
classmethods as factory functions?
Alternatively, could you subclass the object with each
subclass taking different types of input?
The reason for these suggestions is that a class that needs multiple
constructors is usually loading from network or data store (in which
case use factory methods) or has some fundamentally different form of
internal data storage which should be split into two subclasses.
> 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"
So you could have a LetterAward and a StringAward?
(Or just convert the category to a string and use '1','2' etc
instead?
> 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
> 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
> ?
It works, but has several problems with regard to maintainability,
not least being the potential of multiple if/elif options and having
to keep the inputs in step - the same 3 possible inputs. If you add
a new category you need to add a new input check. etc. It would
probably be better in this specific case to just create the
awards class with a dict. But I know this is just a toy so lets
not get bogged down in example specific details.
But the point is that this is often a problem with this type of
overloaded initialiser. You wind up giving yourself maintenance headaches.
> My second question is if a class can have more than one class variable,
Sure, as many as you like.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list