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

2

I'm having the following problem, I have a class letter and I use the magic methods eq , ne , le , lt , gt to be able to compare the value of two cards and also to be able to use the sort function, and this works the way I expected but when I need use the remove method from a list to remove a letter simply or remove the wrong letter or remove none. Here is a portion 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)
    
asked by anonymous 29.06.2018 / 15:22

1 answer

2

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

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

One solution would be to look at the suit when the shackles are the same. For example:

def __eq__(self, other):
    if self.manilha == other.manilha:
        return self.suit == other.suit
    return False
    
10.07.2018 / 02:45