TypeError关于改组纸牌的参数数量

问题描述 投票:0回答:1

我正在尝试编写一个程序,该程序:1.一种创建一副纸牌的功能2.随机更改卡片组中卡片顺序的功能。3.一项功能,可从卡组中删除第一张card_count卡并将其作为列表返回。

对于第一个功能,一切正常,但是对于后两个功能,两个都给我一个错误消息,例如TypeError: deal_card() takes 1 positional argument but 2 were given

您能否看一下我的程序并注意出什么问题了?

后两个功能的正确结果应该是:

> deck2.shuffle_deck()
>>[A of ♠, 10 of ♠, 3 of ♠, 7 of ♠, 5 of ♠, 4 of ♠, 8 of ♠, J of ♠, 9 of ♠, Q of ♠, 6 of ♠, 2 of ♠, K of ♠]

>>deck2.deal_card(7)
>>>[A of ♠, 10 of ♠, 3 of ♠, 7 of ♠, 5 of ♠, 4 of ♠, 8 of ♠]

我的代码:

import random
from random import shuffle


class RankError(Error):
    pass
class SuitError(Error):
    pass
class NoCardsError(Error):
    pass

all_rank = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
all_suit = ["♠", "♥", "♦", "♣"]
hand = []

class PlayingCard:
    def __init__(self, rank, suit):
        if str(rank) not in all_rank:
            raise RankError("Invalid rank!")
        if suit not in all_suit:
            raise SuitError("Invalid suit!")
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return self.rank + " of " + self.suit

    def __repr__(self):
        return "%r of %r" % (self.rank, self.suit)


class Deck:
    def __init__(self, suit = all_suit):
        self.cards = [PlayingCard(rank, one_suit) for rank in all_rank
                                                    for one_suit in suit]

    def __repr__(self):
        return "%r of %r" % (self.rank, self.suit)

    def shuffle_deck():
        self.shuffled_cards = random.shuffle(self.cards)

    def deal_card(card_count):
        if card_count > len(cards):
            raise NoCardsError("Cannot deal 7 cards. The deck only has 6 cards left!")
        else:
            hand = hand.append(cards.pop())
            return hand
python
1个回答
0
投票

您在某些地方忘记了self

def shuffle_deck(self):  # here
    self.shuffled_cards = random.shuffle(self.cards)

def deal_card(self, card_count):  # here
    if card_count > len(self.cards):  # here
        raise NoCardsError("Cannot deal 7 cards. The deck only has 6 cards left!")
    else:
        hand = hand.append(self.cards.pop())  # here
        return hand

可能还有其他错误,但是self上缺少deal_card是导致异常的原因。

© www.soinside.com 2019 - 2024. All rights reserved.