end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

組込みの __hash__ , __eq__ for python で、objectをhashのkeyに設定

以下の通りです

#!python
# -*- coding: utf-8 -*-

def main():
    states = {}

    coords = ((1,2),(3,4),(5,6),(7,8))
    for coord in coords:
        state = State( coord[0],coord[1])
        states[state] = "%d-%d" % coord

    print( states )
    
    tmp_state = State(3, 4)
    print( states[tmp_state] )
        
class State():
    def __init__(self, row=-1, col=-1):
        self.row = row
        self.col = col

    def __hash__(self):
        return hash((self.row, self.col))

    # print()時に呼ばれます. https://yumarublog.com/python/str-repr/
    def __repr__(self):
        return "<State: [{}, {}]>".format(self.row, self.col)

    def __eq__(self, other):
        return self.row == other.row and self.col == other.col

if __name__ == "__main__":
    main()

ちなみに「__hash__」がないと、以下のerrorとなります

Traceback (most recent call last):
  File "foo.py", line 36, in <module>
    main()
  File "foo.py", line 11, in main
    states[state] = "%d-%d" % coord
TypeError: unhashable type: 'State'

ちなみに「__eq__」がないと、以下のerrorとなります

Traceback (most recent call last):
  File "foo.py", line 33, in <module>
    main()
  File "foo.py", line 15, in main
    print( states[tmp_state] )
KeyError: <State: [3, 4]>