2015-02-07 63 views
0

我为卡片游戏编写了以下代码。我在运行程序时没有遇到任何错误。不过,我想改善一件事。对于“getSuit”方法,我怎么能得到像“Clubs”这样的西装的全名,而不是像'c'这样的简称?如何在Python中以全名而不是简称命名

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

根据你所拥有的,最简单的方法很可能是这样的:

def getSuit(self): # Obtain the suit of the card 
    return Card.suit[self.suit] 

但是,请记住,你是混合实例变量和类变量。如果您不知道这意味着什么,那么您应该查看this stackoverflow thread

+0

谢谢,它的工作原理。 – 2015-02-08 21:08:06

相关问题