I have a requirement that I have to write two functions with the same name in Python. How should I do it?
class QueueCards:
def __init__(self):
self.cards = []
def Add(self, other):
self.cards.insert(0, other)
def Add(self, listCards, numCards):
for i in numCards:
card = listCards.GetCard(i)
self.Add(card)
Count()
is the size of the queue.
Python supports both function and operator overloading. In function overloading, we can use the same name for many Python functions but with the different number or types of parameters. With operator overloading, we are able to change the meaning of a Python operator within the scope of a class.
In C you can't have two functions with the same name, at all. In C++, it's entirely possible as long as the function function signature is different, ie two functions having the same name but different set of parameters.
Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.
Yes, we can define multiple methods in a class with the same name but with different types of parameters.
You can't do it. At least, not in the same namespace (i.e.: same module, or same class). It seems you are trying to do something you've learned in one language and are trying to apply it to Python.
Instead, you can have Add
take a variable number of arguments, so you can do different things depending on what was passed in.
def Add(self, *args):
if len(args) == 1:
item = args[0]
self.cards.insert(0, item)
elif len(args) == 2):
listCards, numCards = args
for i in numCards:
card = listCards.GetCard(i)
self.cards.insert(0, card)
Personally I think it is better to have two functions because it avoids ambiguity and aids readability. For example, AddCard
and AddMultipleCards
.
Or, perhaps even better, a single function that you use for any number of cards. For example, you can define Add
to take a list of cards, and you add them all:
def Add(self, *args):
for card in args:
self.cards.insert(0, card)
Then, call it with either a single card:
self.Add(listCards.GetCard(0))
... or, a list of cards:
list_of_cards = [listCards.GetCard(i) for i in range(len(listCards))]
self.Add(*list_of_cards)
You appear to be asked to do function overloading, which is simply not something that Python supports. For more information about function overloading in Python, see this question: Python function overloading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With