这个问题在这里已有答案:
我正在写一个创造扑克手的引擎,我希望每只手只包含独特的牌,即使我是从多个甲板上画画的
我的问题是,这段代码
for z in range(dr):
if self.cards[-1] not in drawcards:
drawcards[z] = self.cards.pop()
不会将具有西装x且值y的卡登记为等于具有西装x和值y的另一张卡
这是我的卡类:
class Card:
"""A class containing the value and suit for each card"""
def __init__ (self, value, suit):
self.value = value
self.suit = suit
self.vname = value_names[value]
self.sname = suit_names[suit]
def __str__(self):
#Irrelevant
def __repr__(self):
#Irrelevant
如何使我的程序寄存器卡a适合x,值y等于卡b,适合x和值y?
编辑:对于将来看这个问题的人,除了__eq__
,
def __hash__(self):
return hash((self.value, self.suit))
是for循环中指定的相等的必要条件
您需要在类上定义__eq__
来处理比较。这是docs。您可能也想要实现__hash__
。文档更多地讨论这个问题。
def __eq__(self, other):
# Protect against comparisons of other classes.
if not isinstance(other, __class__):
return NotImplemented
return self.value == other.value and self.suit == other.suit