2013-10-05 37 views
1

我有这三个Python类:父运行类方法

class Card(object): 
    RANKS = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] 
    SUITS = ["c", "d", "h", "s"] 
    def __init__(self, rank, suit): 
     self.rank = rank 
     self.suit = suit 

    def __str__(self): 
     return self.rank + self.suit 

    def __lt__(self, other): 
     return self.value < other.value 

    def __gt__(self, other): 
     return self.value > other.value 

    @property 
    def value(self): 
     return RANKS.index(self.rank) + SUITS.index(self.suit)/4 


class Hand(object): 
    def __init__(self, cards = []): 
     self.cards = cards 
     self.tricks = 0 

    def __str__(self): 
     return " ".join([str(card) for card in self.cards]) 

    def add(self, card): 
     self.cards.append(card) 

    def remove(self, card): 
     self.cards.remove(card) 


class Deck(Hand): 
    def populate(self): 
     for rank in Card.RANKS: 
      for suit in Card.SUITS: 
       self.add(Card(rank, suit)) 

但是当我运行这段代码:

deck1 = Deck() 
deck1.populate() 
hand1 = Hand() 
print(hand1) 

卡打印的整个甲板。 Hand类似乎正在运行populate(self)。为什么?

+3

您在'Hand .__ init __()'中使用可变默认值;卡片本质上是一个全球性的。 –

回答

1

你的问题是在这里:

def __init__(self, cards = []): 
     self.cards = cards 
     self.tricks = 0 

你看,像def __init__(self, cards=[]): Python的函数定义默认参数仅计算一次,当函数的定义是通过解释加载,所以他们的行为有点全球十岁上下。还要注意,该列表是一个可变对象,因此,根据定义,它可以更改它的元素。结果,当您拨打self.cards.append(card)时,它会附加到一次评估,每次都是相同的列表。 解决方法如下:

def __init__(self, cards=None): 
    if cards is None: 
     cards = [] 
    self.cards = cards 
    self.tricks = 0