所以我一直在閱讀本書,並將本書中的代碼完全重新輸入到Notepad ++中,然後在命令行中運行。有一些東西在擾亂我。對於一個代碼似乎不起作用,我正在複製它幾乎完全如書中所述。用於絕對初學者的Python第3版第9章示例3似乎不起作用
# example 3
# card game 2.0
# Aims: Learn about: Inheritance, Base Class, Derived Class
class Card(object):
""" A playing card. """
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
SUITS = ["c", "d", "h", "s"]
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
rep = self.rank + self.suit
return rep
class Hand(object):
""" A hand of playing cards. """
def __init__(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + "\t"
else:
rep = "<empty>"
return rep
def clear(self):
self.cards = []
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
class Deck(Hand):
""" A Deck of Playing Cards"""
def populate():
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank, suit)
def shuffle(self):
import random
random.shuffle(self.cards)
def deal(self, hands, per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand)
else:
print("Can't continue deal. Out of cards!")
# main
deck1 = Deck()
print("Created a new deck.")
print("Deck:")
print(deck1)
deck1.populate
print("\nPopulated the deck.")
print("Deck:")
print(deck1)
我已經創建了3類卡片,手和甲板。在程序的主要部分,當我嘗試調用方法「填充」時,方法應該調用並從Card類中遍歷類atrributes的列表,並在打印deck1時向我提供可能的卡片列表,但是我是總是回到這是爲什麼呢?
我的第二個問題是,有時我似乎得到'def shuffle(self)'的語法錯誤,而且我看到這種方法沒有問題。
_「不過我總是取回爲什麼是這樣的話?」 _對不起,我不明白這句話的意思是什麼。 – Kevin 2014-12-03 20:36:31