How can I make my classes usable as dict keys?

前端 未结 2 916
轮回少年
轮回少年 2020-12-06 10:32
class A():
   def __init__(self, data=\'\'):
       self.data = data  

   def __str__(self):
       return str(self.data)

d = {}  
elem = A()  
d[elem] = \'abc\'           


        
2条回答
  •  遥遥无期
    2020-12-06 10:49

    What you did should work, as long as you don't override the __hash__() and __eq__() methods. It will use object identity as equality. If you want a different notion of equality, you can override the __hash__() and __eq__() methods of your class.

提交回复
热议问题