我有这三个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)
。为什么呢?
答案 0 :(得分:1)
你的问题在这里:
def __init__(self, cards = []):
self.cards = cards
self.tricks = 0
你会看到,在Python的函数定义中,如def __init__(self, cards=[]):
,当函数定义由解释器加载时,默认参数只被评估一次,因此它们的行为类似于global-ish。另请注意,列表是一个可变对象,因此,根据定义,它可以更改它的元素。结果,当你调用self.cards.append(card)
时,它会在每次评估时附加到此列表。
解决方案是:
def __init__(self, cards=None):
if cards is None:
cards = []
self.cards = cards
self.tricks = 0