python判断两个对象是否为相等,Python集合([])如何检查两个对象是否相等?对象需要定义什么方法来自定义?...

I need to create a 'container' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objects are deemed to be identical, one (either one) is removed. My first thought was to use a set([]) as the containing object, to complete this requirement.

However, the set does not remove one of the two identical object instances. What must I define to create one?

Here is the Python code.

class Item(object):

def __init__(self, foo, bar):

self.foo = foo

self.bar = bar

def __repr__(self):

return "Item(%s, %s)" % (self.foo, self.bar)

def __eq__(self, other):

if isinstance(other, Item):

return ((self.foo == other.foo) and (self.bar == other.bar))

else:

return False

def __ne__(self, other):

return (not self.__eq__(other))

Interpreter

>>> set([Item(1,2), Item(1,2)])

set([Item(1, 2), Item(1, 2)])

It is clear that __eq__(), which is called by x == y, is not the method called by the set. What is called? What other method must I define?

Note: TheItems must remain mutable, and can change, so I cannot provide a__hash__()method. If this is the only way of doing it, then I will rewrite for use of immutable Items.

解决方案

I am afraid you will have to provide a __hash__() method. But you can code it the way, that it does not depend on the mutable attributes of your Item.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值