gpt4 book ai didi

python - 父类运行方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:25 24 4
gpt4 key购买 nike

我有这三个 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) 。为什么?

最佳答案

您的问题在这里:

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

你看,在 Python 的函数定义中,如 def __init__(self, cards=[]): 默认参数仅在解释器加载函数定义时计算一次,因此它们的行为是排序的全局的。另请注意,列表是一个可变对象,因此,根据定义,它可以更改其元素。结果,当您调用 self.cards.append(card) 时,它会追加到此一次评估后的列表中,每次都相同。解决办法是:

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

关于python - 父类运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19196289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com