我有一个要求,我必须在 Python 中编写两个同名的函数。我该怎么做?

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() 是队列的大小。

最佳答案

你不能这样做。至少,不在同一个命名空间中(即:同一个模块或同一个类)。您似乎正在尝试用一种语言来做一些您已经学过的事情,并尝试将其应用到 Python 中。
相反,您可以让 Add 接受可变数量的参数,因此您可以根据传入的内容做不同的事情。

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)
我个人认为最好有两个函数,因为它可以避免歧义并有助于可读性。例如, AddCardAddMultipleCards
或者,也许更好,您可以为任意数量的卡片使用单个功能。例如,您可以定义 Add 来获取卡片列表,然后将它们全部添加:
def Add(self, *args):
    for card in args:
        self.cards.insert(0, card)
然后,用一张卡调用它:
self.Add(listCards.GetCard(0))
...或者,卡片列表:
list_of_cards = [listCards.GetCard(i) for i in range(len(listCards))]
self.Add(*list_of_cards)

您似乎被要求执行函数重载,这根本不是 Python 支持的。有关 Python 中函数重载的更多信息,请参阅此问题:Python function overloading

关于python - Python中的两个同名函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34546775/

10-12 18:41
查看更多