[Python] Why does my custom object fail to work as a dictionary key even after implementing...

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use instances of a custom Python class as keys in a dictionary. I've overridden both __hash__() and __eq__() methods, but somehow, dictionary lookups still fail for seemingly identical keys.

    class Book:
    def __init__(self, title, author):
    self.title = title
    self.author = author

    def __eq__(self, other):
    return isinstance(other, Book) and self.title == other.title and self.author == other.author

    def __hash__(self):
    return hash((self.title, self.author))

    book1 = Book("Wings of Fire", "A.P.J. Abdul Kalam")
    book2 = Book("Wings of Fire", "A.P.J. Abdul Kalam")

    books_dict = {book1: "Autobiography"}

    print(book2 in books_dict)


    Since book1 and book2 have the same data and both __eq__ and __hash__ are defined, I expected book2 in books_dict to return True.

    Continue reading...

Compartilhe esta Página