Making Classes Support Comparison Operations
Problem
You’d like to be able to compare instances of your class using the
standard comparison operators (e.g., >=, !=, <=, etc.), but without
having to write a lot of special methods.
Solution
Python classes can support comparison by implementing a special
method for each comparison operator. For example, to
support the >= operator, you define a __ge__() method in the
classes. Although defining a single method is usually no problem,
it quickly gets tedious to create implementations of every possible
comparison operator.
The functools.total_ordering decorator can be used to simplify
this process. To use it, you decorate a class with it, and define __eq__()
and one other comparison method (__lt__, __le__,
__gt__, or __ge__). The decorator then fills in the other comparison
methods for you.
As an example, let’s build some houses and add some rooms to them, and then perform comparisons based on the size of the houses:
fromfunctoolsimporttotal_orderingclassRoom(object):def__init__(self,name,length,width):self.name=nameself.length=lengthself.width=widthself.square_feet=self.length*self.width@total_orderingclassHouse(object):def__init__(self,name,style):self.name=nameself.style=styleself.rooms=list()@propertydefliving_space_footage(self):returnsum(r.square_feetforrinself.rooms)defadd_room(self,room):self.rooms.append(room)def__str__(self):return'{}: {} square foot {}'.format(self ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access