https://gist.github.com/rjurney/1e8454af8e44312d02d7
class FrozenSortedTuple:
"""A frozenset that cares about order of tuples. And is not actually frozen."""
def __init__(self, vals):
if type(vals) not in [list, set, tuple]:
raise Exception('Value not a list or set')
self.vals = list(vals)
def __eq__(self, other):
if len(self.vals) != len(other):
return False
if type(self.vals) != type(other):
return False
if type(other) not in [list, set, tuple]:
return False
other_list = list(other)
for i,item in enumerate(self.vals):
if item != other_list[i]:
return False
return True
在Ipyhon中调用:
In [2]: a = ['a','b']
In [3]: b = ['b','a']
In [4]: c = ['a','b']
In [5]: a == b
Out[5]: False
In [6]: FrozenSortedTuple(a)
Out[6]: <__main__.FrozenSortedTuple instance at 0x103c56200>
In [7]: fa = FrozenSortedTuple(a)
In [8]: fb = FrozenSortedTuple(b)
In [9]: fa == fb
错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-317181571e4d> in <module>()
----> 1 fa == fb
<ipython-input-1-ef99f0af5061> in __eq__(self, other)
15
16 def __eq__(self, other):
---> 17 if len(self.vals) != len(other):
18 return False
19 if type(self.vals) != type(other):
AttributeError: FrozenSortedTuple instance has no attribute '__len__'
我很困惑。
最佳答案
如果您试图直接比较两个FrozenSortedTuples的值的结构和内容,请将other
的所有实例更改为other.vals
。
def __eq__(self, other):
if len(self.vals) != len(other.vals):
return False
if type(self.vals) != type(other.vals):
return False
if type(other.vals) not in [list, set, tuple]:
return False
other_list = list(other.vals)
for i,item in enumerate(self.vals):
if item != other_list[i]:
return False
return True
当然,如果
other
不是一个frozensorteduple,这将无法工作。例如,fa == 23
将不起作用,因为数字23没有“vals”属性。关于python - Python类:为什么不能在__eq __(self,other)内部使用len()方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32510000/