所以,我已经有了基本卡片组,但我在打印过程中遇到了麻烦。我的教授让我们使用 eq 和 str 方法,因此我在我的代码中使用了它。我有什么错误的建议?如何更改主部分以将返回的手中的每张卡转换为字符串,然后仅将其打印出来?
import random
class Deck(object):
"""Represent a deck of 52 playing cards."""
def __init__(self, start_shuffled):
"""Initializes a deck with 52 cards."""
suits=["H","S","D","C"]
ranks= list ( range(2, 11)) + ["J", "Q", "K", "A"]
self.cards=[]
for suit in suits:
for rank in ranks:
self.cards.append(Card(suit, rank))
if start_shuffled:
random.shuffle(self.cards)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def has_card(self, card):
return card in self.cards
def draw_random_card(self):
card=random.choice(self.cards)
self.cards.remove(card)
return card
def draw_hand(self, num_cards):
cards=[ ]
for _ in range(num_cards):
cards.append(self.draw_random_card())
return cards
class Card(object) :
def __init__(self, s , r):
self.suit=s
self.rank=r
def __str__(self):
rep = self.rank + self.suit
return rep
def __eq__(self, other_card):
t1 = self.suit, self.rank
t2 = other_card.suit, other_card.rank
return eq(t1, t2)
def main():
deck1=Deck(True)
print("All the cards in the deck:")
print(deck1.cards)
print("Does the deck have the Queen of Hearts? True or False")
print(deck1.has_card(Card("H", "Q")))
card=deck1.draw_random_card()
print("A random card from the deck:")
print(card)
if deck1.has_card(card):
print("Something bad happened...")
print(card, "Shouldn't be in the deck anymore.")
print("A hand of six random cards:")
print (deck1.draw_hand(6))
if __name__=="__main__":
main()
答案 0 :(得分:2)
你在这一行得到NameError
:
return eq(t1, t2)
因为没有这样的功能eq
。只需使用相等运算符。
return t1 == t2
然后,你在这一行得到了一个TypeError:
rep = self.rank + self.suit
因为有时rank
是一个整数,并且您无法将整数和字符串一起添加。在连接之前将rank
转换为字符串。
rep = str(self.rank) + self.suit
然后,当您打印整个套牌时,它会显示类似<__main__.Card object at 0x00000000024A19E8>
的内容,因为当您在集合中打印对象时,对象不会使用__str__
。为您的卡实施__repr__
方法。
def __repr__(self):
return self.__str__()
现在你应该获得更好的输出。
All the cards in the deck:
[10H, QS, 9D, 10C, 5S, AS, 5C, 10D, AC, 9C, 3H, 3D,
6H, JH, AD, 7D, KC, 7H, JD, 9H, 8H, 3C, 3S, 4H, 8C,
QD, 6C, 9S, QC, 6D, JS, 7S, 5H, 10S, KH, 2C, 7C, JC,
6S, 4D, 4S, 5D, 4C, AH, 2S, 8S, 8D, KS, 2D, KD, 2H, QH]
Does the deck have the Queen of Hearts? True or False
True
A random card from the deck:
3H
A hand of six random cards:
[3D]
答案 1 :(得分:1)
夫妻俩:
__str__
更改为__repr__
。我做了这个,它开始打印出来相当正常的我。对__str__
和__repr__
here __eq__
,但Kevin已经解决了这些问题。