【问题标题】:Check for duplicate instances of class by their attributes [duplicate]通过属性检查类的重复实例[重复]
【发布时间】:2019-03-22 20:35:31
【问题描述】:

我正在编写一个引擎来创建扑克牌,我希望每手牌都只包含独特的牌,即使我从多个牌组中抽牌

我的问题是,这段代码

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

如何让我的程序注册花色 x 和值 y 的卡 a 等于花色 x 和值 y 的卡 b?

编辑: 对于以后看这个问题的人,除了__eq__

def __hash__(self):
        return hash((self.value, self.suit))

对于 for 循环中指定的相等性是必需的

【问题讨论】:

    标签: python oop equality


    【解决方案1】:

    你需要在你的类上定义__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
    

    【讨论】:

    • 记住other可以是任何类型。
    • 感谢@cglacet,我编辑了我的答案以说明这一点。
    • 这个__eq__ 实现严重损坏。我会冒昧地修复它。
    • @Aran-Fey 解释为什么您的建议更受欢迎而不是居高临下,这对我(可能还有其他人)会更有帮助。
    • 我认为您的编辑没有必要。如果您打算从此类继承,则需要决定是使用self.__class__ 还是__class__。使用__class__ 仍将解析回子类中的父类,而self.__class__ 将是被实例化的类。那么 return False 和 raise NotImplemented 的区别又是基于场景的个人偏好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2023-01-08
    • 2012-04-04
    • 2011-10-26
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多