我试图利用来自集合模块的python deque,其中deque内的元素是自定义类实例。我想知道如何擦除/删除对象?如果可以,我可以使用诸如deque.remove(element)之类的内置方法吗?它将如何找到我的自定义对象?
class Buffer(object):
""" """
def __init__(self, name, size_total, size_in_cache):
self.name = name
self.size_total = size_total
class Storage(object):
"""
"""
def __init__(self, capacity):
self.CAPACITY = capacity
self.contents = collections.deque()
self.capacity_used = 0
def push_to_contents(self, buffer_name, buffer_size):
buf = Buffer(buffer_name, buffer_size)
self.contents.appendleft(buf)
def delete_from_contents(self, buffer_name)
""" HOW??
How can I use self.contents.remove() here>
"""
The way
collections.deque.remove
operates is by comparing the argument to each item in the deque. If it finds something which is equal to the argument, it removes it. Otherwise, it raises aValueError
.Since a
Buffer
object, as you've implemented it, doesn't know how to compare itself with other objects, Python defaults (using theobject
parent class) to comparing theid
values.However, if you were to implement the
__eq__
method for your class, you could accomplish what you're looking for.例如。,
编辑:
This is all fine and good if you're using Python 3. In Python 2, you have to implement
__ne__
("not equal") as well. It can be as simple asPython 3自动为您解决此问题。