我目前正在阅读“如何像计算机科学家那样思考”一书
现在我从书中得到了这段代码
class Card:
suitList = ["Clubs", "Diamonds", "Hearts", "Spades"]
rankList = ["narf", "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"]
def __init__(self, suit=0, rank=0):
self.suit = suit
self.rank = rank
def __str__(self):
return (self.rankList[self.rank] + " of " + self.suitList[self.suit])
def __cmp__(self, other):
#check the suits
if self.suit > other.suit: return 1
if self.suit < other.suit: return -1
#suits are the same... check ranks
if self.rank > other.rank: return 1
if self.rank < other.rank: return -1
#ranks are the same... it's a tie
return 0
class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
self.cards.append(Card(suit, rank))
def printDeck(self):
for card in self.cards:
print card
def __str__(self):
s = ""
for i in range(len(self.cards)):
s = s + " "*i +str(self.cards[i]) + "\n"
return s
def shuffle(self):
import random
nCards = len(self.cards)
for i in range(nCards):
j = random.randrange(i, nCards)
self.cards[i], self.cards[j] = self.cards[j], self.cards[i]
def removeCard(self, card):
if card in self.cards:
self.cards.remove(card)
return 1
else:
return 0
def popCard(self):
return self.cards.pop()
def isEmpty(self):
return (len(self.cards) == 0)
def deal(self, hands, nCards=999):
nHands = len(hands)
for i in range(nCards):
if self.isEmpty(): break
card = self.popCard()
hand = hands[i % nHands]
hand.addCard(card)
class Hand(Deck):
def __init__(self, name=""):
self.cards = []
self.name = name
def addCard(self,card):
self.cards.append(card)
def __str__(self):
s = "Hand " + self.name
if self.isEmpty():
return s + "is empty\n"
else:
return s + " contains\n" + Deck.__str__(self)
class CardGame:
def __init__(self):
self.deck = Deck
self.deck.shuffle()
deck = Deck()
deck.shuffle()
hand = Hand("frank")
deck.deal([hand], 5)
print hand
现在我理解了自己的位,但我不明白
self.deck.shuffle()
来自于__init__
函数中的原因。我需要的是对课程和日常用途的一个很好的解释,它将向我解释。
答案 0 :(得分:2)
__init__
函数执行名称所暗示的操作:初始化类的实例。
一个类是cookie切割器,因为对象是cookie:它是创建内存中实例并与之交互的蓝图。
什么是适合的课程和对象?它们将数据和功能封装在一起。
计算机科学中的每种语言都试图帮助您完成一件事:管理复杂性。它封装了细节并将其隐藏在用户之外,因此他们只需要考虑该类如何映射到他们的真实生活体验中,以便有效地使用它。
这是另一个想法:不使用类。 Python是面向对象和函数式编程的很好的混合体。如果您不理解类,请在没有它们的情况下编写Python。继续学习直到你看到灯光,然后开始将它们融入你的设计中。