Sobes.tech
Junior — Middle

Millised sammud on vajalikud, et teie enda klassi eksemplar saaks kasutada Python sõnastikus võtmena?

sobes.tech AI

Vastus AI-lt

To allow an instance of your own class to be used as a key in a Python dictionary, it must be hashable and comparable. To do this, you need to implement the __hash__() and __eq__() methods in the class. The __hash__ method should return a unique integer value considering its significant attributes, and __eq__ should define the equality of objects.

Example:

class MyKey:
    def __init__(self, id):
        self.id = id

    def __hash__(self):
        return hash(self.id)

    def __eq__(self, other):
        return isinstance(other, MyKey) and self.id == other.id

# Usage
my_dict = {}
key1 = MyKey(1)
key2 = MyKey(1)
my_dict[key1] = 'value'
print(my_dict[key2])  # Will output 'value', because key1 == key2

It is important that objects are immutable with respect to the attributes used in hashing, otherwise the dictionary may not work correctly.