How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this?(Python set([]) 如何检查两个对象是否相等?一个对象需要定义哪些方法来自定义它?)
问题描述
我需要在 Python 中创建一个容器"对象或类,它会记录我还定义的其他对象.此容器的一个要求是,如果两个对象被认为是相同的,则删除一个(其中一个).我的第一个想法是使用 set([])
作为包含对象,来完成这个要求.
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?
这是 Python 代码.
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))
口译员
>>> set([Item(1,2), Item(1,2)])
set([Item(1, 2), Item(1, 2)])
很明显,x == y
调用的__eq__()
并不是集合调用的方法.什么叫做?我还必须定义什么其他方法?
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?
注意:Item
s 必须保持可变,并且可以更改,因此我无法提供 __hash__()代码> 方法.如果这是唯一的方法,那么我将重写以使用不可变的
Item
s.
推荐答案
恐怕你得提供一个 __hash__()
方法.但是你可以这样编码,它不依赖于你的 Item
的可变属性.
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
.
这篇关于Python set([]) 如何检查两个对象是否相等?一个对象需要定义哪些方法来自定义它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python set([]) 如何检查两个对象是否相等?一个对象需要定义哪些方法来自定义它?


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01