我正在尝试以下问题:
Implement a CardHand class that supports a person arranging a group of cards in his or her hand. The simulator should represent the sequence of cards using a single positional list ADT so that cards of the same suit are kept together. Implement this strategy by means of four “fingers” into the hand, one for each of the suits of hearts, clubs, spades, and diamonds, so that adding a new card to the person’s hand or playing a correct card from the hand can be done in constant time. The class should support the following methods:
- add card(r, s): Add a new card with rank r and suit s to the hand.
- play(s): Remove and return a card of suit s from the player’s hand; if there is no card of suit s, then remove and return an arbitrary card from the hand.
- iter (): Iterate through all cards currently in the hand.
- all of suit(s): Iterate through all cards of suit s that are currently in the hand.
class CardHand:
"""Class representing a hand of cards"""
class _Card:
"""Class representing a single card"""
suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades']
ranks= ['Ace','2','3','4','5','6','7','8','9','10','11','Jack', 'Queen', 'King']
def __init__(self,suit,rank):
self._suit = suit
self._rank = rank
def __str__(self):
return self._rank + ' ' + self._suit
def __init__(self):
self._hand = PositionalList()
self._size = 0
def _validate(self,s,r):
card = self._Card(s,r)
if not card._suit in suits:
raise ValueError("Such card doesn't exist")
if not card._rank in ranks:
raise ValueError("Invalid card value")
return card
def add_card(self,s,r):
return self._hand.add_first(self._Card(s,r))
print(CardHand.add_card('s', '4'))
我有位置列表的代码和它的基础,但它的行太多了,所以我不会发布它。我一直在其他任务中使用相同的位置列表,它一直在工作。只是问你是否明白为什么这段代码会抛出这个错误:
"Missing one required positional argument "r".
您将调用一个实例方法作为静态方法。而不是
你应该这么做
^{pr2}$原因如下:中的参数
self
引用调用
add_card()
的实例,在上面的后一个示例中,ch
以self
的形式无形地传递到方法中。事实上,以下两种情况相当:所以当你做
CardHand('s', '4')
时,你不是在实例上调用它,而是在类本身上调用它。所以,很自然,python会感到困惑,然后说“我应该看到的第三个论点在哪里?”,这就导致了你的错误。在顺便说一句,如果您想创建一个静态方法-一个可以在类本身上调用的静态方法,而不是在类的实例上调用的方法(因此,没有
self
参数),则可以使用修饰符:或者,也可以有一个类方法,它类似于实例方法,但将类的类型作为参数,而不是类的实例:
前者偶尔有用。后者只有在处理多态性和继承性时才真正相关。在
相关问题 更多 >
编程相关推荐