【发布时间】:2015-12-07 05:16:48
【问题描述】:
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
在 iPython 中调用:
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__'
我很困惑。
【问题讨论】:
-
问题不在于“你不能在
__eq__中调用len”。问题是“你根本不能在任何地方打电话给len”,因为你从来没有为这门课实施过它。len(fa)会以同样的方式在主范围内失败。 -
为什么所有全局函数都会在一个类中消失?
-
哦!我知道了。谢谢。
-
等等,我没有。我不是在 self 上调用 len(),也不是在调用 ... 是的,我是。好,谢谢!您可以在答案而不是评论中做出答案吗?
标签: python class python-2.7 oop variable-length