如何使用自定义类实例的python collections.deque?

我试图利用来自集合模块的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 a ValueError.

    Since a Buffer object, as you've implemented it, doesn't know how to compare itself with other objects, Python defaults (using the object parent class) to comparing the id values.

    However, if you were to implement the __eq__ method for your class, you could accomplish what you're looking for.

    例如。,

    def __eq__(self, other):
        if isinstance(other, Buffer):
            return self.name == other.name and self.size_total == other.size_total
        elif isinstance(other, str):
            return self.name == other
        else:
            return NotImplemented
    

    编辑:

    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 as

    def __ne__(self, other):
        return not self == other
    

    Python 3自动为您解决此问题。