我为纸牌游戏编写了以下代码。运行程序时我没有遇到任何错误。但是,有一件事我想改进。对于方法" getSuit",我怎么能得到诉讼的全名,如俱乐部'而不只是像' c'?
这样的简短名称class Card: # One object of class Card represents a playing card
rank =['','Ace','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King']
suit = {'d':'Diamonds', 'c':'Clubs', 'h':'Hearts', 's':'Spades'}
def __init__(self, rank=2, suit=0): # Card constructor, executed every time a new Card object is created
self.rank = rank
self.suit = suit
def getRank(self): # Obtain the rank of the card
return self.rank
def getSuit(self): # Obtain the suit of the card
return self.suit
def bjValue(self): # Obtain the Blackjack value of a card
Value = {'Ace':'1', 'Two':'2', 'Three':'3', 'Four':'4', 'Five':'5', 'Six':'6', 'Seven':'7', 'Eight':'8', 'Nine':'9', 'Ten':'10', 'Jack':'10', 'Queen':'10', 'King':'10'}
return min(self.rank, 10)
def __str__(self): # Generate the name of a card in a string
return "%s of %s" % (Card.rank[int(self.rank)], Card.suit[self.suit])
c1 = Card(1,'c')
print(c1)
print(c1.getRank())
print(c1.getSuit())
print(c1.bjValue())
# Output as below
>>> ================================ RESTART ================================
>>>
Ace of Clubs
1
c
1
>>>
答案 0 :(得分:0)
根据你所拥有的,最简单的方法可能是这样的:
def getSuit(self): # Obtain the suit of the card
return Card.suit[self.suit]
但是,请记住,您正在混合实例变量和类变量。如果您不知道这意味着什么,请查看this stackoverflow thread。