简体   繁体   中英

Unique class instances in Python3

suppose I have a class definition like this

class structure:
    def __init__(self, handle):
        self.handle = handle

How can I use numpy.unique or another tool of Python3 to find unique elements in a list of instances of this class? The comparison should be done with respect to the value of the 'handle' field.

numpy.unique is not the best tool for custom classes. Make your instances hashable (implementing __hash__ and __eq__ ), then use a set to reduce a list of instances to unique values:

class structure:
    def __init__(self, handle):
        self.handle = handle

    def __hash__(self):
        return hash(self.handle)

    def __eq__(self, other):
        if not isinstance(other, structure):
            # only equality tests to other `structure` instances are supported
            return NotImplemented
        return self.handle == other.handle

Sets efficiently can detect duplicates via the hash, confirming that the objects with the same hash are also equal first.

To get the unique instances, simply call set() on a sequence of instances:

unique_structures = set(list_of_structures)

Demo:

>>> class structure:
...     def __init__(self, handle):
...         self.handle = handle
...     def __hash__(self):
...         return hash(self.handle)
...     def __eq__(self, other):
...         if not isinstance(other, structure):
...             # only equality tests to other `structure` instances are supported
...             return NotImplemented
...         return self.handle == other.handle
...     def __repr__(self):
...         return '<structure({!r})>'.format(self.handle)
...
>>> list_of_structures = [structure('foo'), structure('bar'), structure('foo'), structure('spam'), structure('spam')]
>>> set(list_of_structures)
{<structure('bar')>, <structure('foo')>, <structure('spam')>}

Do take into account that the hash of any structure instance stored in a set or used a dictionary key must not change ; not altering the handle attribute during the lifetime of an instance is the easiest way to ensure this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM