-1

I'm writing an engine that creates poker hands, and I'd like each hand to contain only unique cards even though I'm drawing from multiple decks

My problem is, this code

for z in range(dr):
    if self.cards[-1] not in drawcards:
        drawcards[z] = self.cards.pop()

does not register a card with suit x and value y as being equal to another card with suit x and value y

this is my card 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

how can I make my program register card a with suit x and value y as equal to card b with suit x and value y?

Edit: For people looking at this question in the future, in addition to __eq__,

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

is necessary for the equality specified in the for loop to work

Alec
  • 8,529
  • 8
  • 37
  • 63

1 Answers1

1

You need to define __eq__ on your class to handle the comparisons. Here are the docs. You'll likely also want to implement __hash__ as well. The docs talk more about that.

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
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
schillingt
  • 13,493
  • 2
  • 32
  • 34
  • 2
    Remember that `other` can be of any type. – cglacet Mar 22 '19 at 20:41
  • Thanks @cglacet, I edited my answer to account for that. – schillingt Mar 22 '19 at 20:43
  • This `__eq__` implementation is majorly broken. I'll take the liberty to fix it. – Aran-Fey Mar 22 '19 at 21:04
  • 1
    @Aran-Fey it would be more helpful to me (and likely others) to explain why your suggestions are preferred rather than come across condescending. – schillingt Mar 22 '19 at 21:16
  • I don't think your edit was warranted. If you plan on inheriting from this class you will need to make a decision on whether to use `self.__class__` or `__class__`. Using `__class__` will still resolve back to the parent class in subclasses while `self.__class__` will be the class that was instantiated. Then the difference between return False or raising NotImplemented is again personal preference based on the scenario. – schillingt Mar 22 '19 at 21:21
  • Well, feel free to roll back. – Aran-Fey Mar 22 '19 at 21:22