码迷,mamicode.com
首页 > 其他好文 > 详细

Decks

时间:2014-10-06 17:49:50      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

Now that we have Card objects, the next step is to define a class to represent decks. Since a deck is made up cards, a natural choice is for each Deck object to contain a list of cards as an attribute. The following is a class definition for Deck. The init method creates the attribute cards and generates the standard set of fifty-two cards:

class Deck:
    """represents a standard Deck
       instance attributes: cards """
    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1,14)
            card = Card(suit,rank)
            self.cards.append(card)

The easiest way to populate the deck is with a nested loop. The outer loop enumerates the suits from 0 to 3. The inner loop enumerates the ranks from 1 to 13. Each iteration of the inner loop creates a new Card with current suit and rank, and appends it to self.cards.

Printing the deck

Here is a str method for Deck:

def __str__(self):
        temp = []
        for card in self.cards:
            temp.append(str(card))
        return \n.join(temp)

The method demonstrates an efficient way to accumulate a large string, by building a list of strings and then using join. The built-in function str invokes the __str__ method on each card and returns the string representation. Since we invoke join on a newline character, the cards are separated by newlines.

bubuko.com,布布扣

........

bubuko.com,布布扣

 

from Thinking in Python

 

 

Decks

标签:style   blog   http   color   io   ar   for   sp   div   

原文地址:http://www.cnblogs.com/ryansunyu/p/4008194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!