【发布时间】:2013-12-20 07:01:59
【问题描述】:
我正在为 python 编写一个Queue 数据结构,纯粹是为了学习目的。这是我的class。当我比较两个 Queue 对象是否相等时,出现错误。我认为错误会弹出,因为我没有比较 None 在我的 __eq__ 中。但是我如何检查 None 和 return 一致。事实上,我在后台使用list 并调用它的__eq__,认为它应该像这里所示那样小心,但它没有
>>> l=[1,2,3]
>>> l2=None
>>> l==l2
False
这是我的课:
@functools.total_ordering
class Queue(Abstractstruc,Iterator):
def __init__(self,value=[],**kwargs):
objecttype = kwargs.get("objecttype",object)
self.container=[]
self.__klass=objecttype().__class__.__name__
self.concat(value)
def add(self, data):
if (data.__class__.__name__==self.__klass or self.__klass=="object"):
self.container.append(data)
else:
raise Exception("wrong type being added")
def __add__(self,other):
return Queue(self.container + other.container)
def __iadd__(self,other):
for i in other.container:
self.add(i)
return self
def remove(self):
return self.container.pop(0)
def peek(self):
return self.container[0]
def __getitem__(self,index):
return self.container[index]
def __iter__(self):
return Iterator(self.container)
def concat(self,value):
for i in value:
self.add(i)
def __bool__(self):
return len(self.container)>0
def __len__(self):
return len(self.container)
def __deepcopy__(self,memo):
return Queue(copy.deepcopy(self.container,memo))
def __lt__(self,other):
return self.container.__lt__(other.container)
def __eq__(self, other):
return self.container.__eq__(other.container)
但是当我尝试使用上面的类进行比较时,我得到:
>>> from queue import Queue
>>> q = Queue([1,2,3])
>>> q
>>> print q
<Queue: [1, 2, 3]>
>>> q1 = None
>>> q==q1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "queue.py", line 65, in __eq__
return self.container.__eq__(other.container)
AttributeError: 'NoneType' object has no attribute 'container'
>>>
【问题讨论】:
标签: python class object comparison equals