Problems with __eq__, __lt__, etc. and the method removes from the list object

Asked

Viewed 192 times

2

I’m having the following problem, I have a letter class and use the magic methods eq, ne, le, it’s, ge, gt to be able to compare the value of two cards and also to be able to use the Sort function, and for that it works the way I expected but when I need to use the remove method from a list to remove a card simply either remove the wrong card or remove none. Follows a part of the class code:

class Card(object):

def __init__(self, game, value, suit, args={}):
    super(Card, self).__init__()
    self.front = pygame.image.load("images/cards/card_{}_{}.png".format(
        suit, value)).convert()
    self.back = back.convert()
    self.image = self.front
    self.rect = self.front.get_rect(**args)
    self.sound = sounds["card_place_1"]
    self.game = game
    self.value = value
    self.suit = suit
    self.moved = False
    self.visible = True

def __eq__(self, other):
    return self.manilha == other.manilha

def __ne__(self, other):
    return self.manilha != other.manilha

def __lt__(self, other):
    return self.manilha < other.manilha

def __le__(self, other):
    return self.manilha <= other.manilha

def __gt__(self, other):
    return self.manilha > other.manilha

def __ge__(self, other):
    return self.manilha >= other.manilha

@property
def manilha(self):
    if self.image == self.back:
        return -1
    elif "4567qjka23".find(self.value) == "34567qjka2".find(
            self.game.vira.value):
        return {"diamonds": 10, "spades": 11, "hearts": 12, "clubs": 13}[
            self.suit]
    else:
        return "4567qjka23".find(self.value)

1 answer

2


The problem is simple. The method list.remove searches the object you passed by parameter in the list and removes it. To know that it found the correct object, it uses the method __eq__ to compare the object that was passed with each object in the list.

The problem with your code is that the method __eq__ returns true for different objects. The method manilha mostly uses only the attribute value to calculate the object identifier, ie 2 cards with same value and suit different will be pointed out as the same card (after all they return the same value in the method manilha).

A solution would be to look at the Suit when the shackles are equal. For example:

def __eq__(self, other):
    if self.manilha == other.manilha:
        return self.suit == other.suit
    return False

Browser other questions tagged

You are not signed in. Login or sign up in order to post.