通过属性检查 class 的重复实例
Check for duplicate instances of class by their attributes
我正在编写一个创建扑克手牌的引擎,我希望每手牌只包含唯一的牌,即使我从多副牌中抽牌
我的问题是,这段代码
for z in range(dr):
if self.cards[-1] not in drawcards:
drawcards[z] = self.cards.pop()
不会将花色为 x 且值为 y 的牌注册为等于另一张花色为 x 且值为 y 的牌
这是我的名片class:
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
如何让我的程序注册花色为 x、价值为 y 的卡片 a 等于花色为 x、价值为 y 的卡片 b?
编辑:
对于以后看这个问题的人,除了__eq__
,
def __hash__(self):
return hash((self.value, self.suit))
对于 for 循环中指定的相等性起作用是必要的
您需要在 class 上定义 __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
我正在编写一个创建扑克手牌的引擎,我希望每手牌只包含唯一的牌,即使我从多副牌中抽牌
我的问题是,这段代码
for z in range(dr):
if self.cards[-1] not in drawcards:
drawcards[z] = self.cards.pop()
不会将花色为 x 且值为 y 的牌注册为等于另一张花色为 x 且值为 y 的牌
这是我的名片class:
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
如何让我的程序注册花色为 x、价值为 y 的卡片 a 等于花色为 x、价值为 y 的卡片 b?
编辑:
对于以后看这个问题的人,除了__eq__
,
def __hash__(self):
return hash((self.value, self.suit))
对于 for 循环中指定的相等性起作用是必要的
您需要在 class 上定义 __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