- 大白话:
Python内部使用集合set可以对可迭代对象进行去重。是在Python内部是调用了__hash__和__eq__方法。
原理就是 调用两个对象的__hash__
方法。如果返回值不同,则说明两个对象不重复。
如果__hash__
方法的返回值相同,则调用两个对象的 __eq__
方法。如果返回值不同,则说明两个对象不重复。如果相同,则两个对象重复
举个例子
# coding:utf-8
class TestUnique(object):
def __init__(self, id, val):
self._id = id
self._val = val
def __hash__(self):
print('{0:s}的__hash__函数被运行了'.format(self._id))
return self._val
def __eq__(self, other):
print('{0:s}的__eq__函数被运行了'.format(self._id))
return self._val == other._val
def __str__(self):
return '{0:s}_{1:d}'.format(self._id, self._val)
if __name__ == '__main__':
t11 = TestUnique('11', 10)
t12 = TestUnique('12', 10)
t2 = TestUnique('2', 20)
test_set = {t11, t12, t2}
print('*' * 25)
for t in test_set:
print(t)
2的__hash__函数被运行了
12的__hash__函数被运行了
11的__hash__函数被运行了
12的__eq__函数被运行了
************************
12_10
2_20
从最后两行可以看到,t11因为与t12重复被去掉了。
t2的__hash__方法的结果和t11和t12不同,所以保留下来。
t11和t12的__hash__方法的结果相同,进一步调用__eq__方法,结果为True,所以判断t11和t12是相同的对象
原址参考:https://blog.csdn.net/feishicheng/article/details/88907705