2014-12-03 34 views
-1

所以我一直在閱讀本書,並將本書中的代碼完全重新輸入到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)'的語法錯誤,而且我看到這種方法沒有問題。

+2

_「不過我總是取回爲什麼是這樣的話?」 _對不起,我不明白這句話的意思是什麼。 – Kevin 2014-12-03 20:36:31

回答

0

你的第一個問題

在程序的主要部分,當我嘗試調用的方法「填充」該方法應該從Card類中調用並運行類atrributes的列表,並在打印deck1時向我提供可能的卡片列表,但是我總是回頭看看爲什麼會出現這種情況?

你是不是調用填入,deck1.populate不會調用它,使用deck1.populate()代替。

而你沒有正確定義的任何話,它應該採取一個參數:

# ... 
def populate(self): 
    # ... 

關於你的第二個問題

我的第二個問題是,有時我似乎得到一個'def shuffle(self)'的語法錯誤,我發現這種方法沒有問題。

你有

  # ... 
      self.add(Card(rank, suit) # <-- Syntax error 

def shuffle(self): 

self.add行缺少一個右括號

+0

謝謝,我猜並沒有完全複製出來...... – firebird92 2014-12-03 21:19:14

0

deck1.populate是一個函數,所以你需要調用它以這樣的方式 deck1.populate()

相關問題