473,785 Members | 2,924 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Boilerplate in rich comparison methods

I'm writing a class that implements rich comparisons, and I find myself
writing a lot of very similar code. If the calculation is short and
simple, I do something like this:
class Parrot:
def __eq__(self, other):
return self.plumage() == other.plumage()
def __ne__(self, other):
return self.plumage() != other.plumage()
def __lt__(self, other):
return self.plumage() < other.plumage()
def __gt__(self, other):
return self.plumage() other.plumage()
def __le__(self, other):
return self.plumage() <= other.plumage()
def __ge__(self, other):
return self.plumage() >= other.plumage()

If the comparison requires a lot of work, I'll do something like this:

class Aardvark:
def __le__(self, other):
return lots_of_work(se lf, other)
def __gt__(self, other):
return not self <= other
# etc.

But I can't help feeling that there is a better way. What do others do?

--
Steven.

Jan 13 '07
11 1600
"Steven D'Aprano" <st***@REMOVE.T HIS.cybersource .com.auescribió en el
mensaje
news:pa******** *************** *****@REMOVE.TH IS.cybersource. com.au...
On Fri, 12 Jan 2007 23:28:06 -0800, Paul Rubin wrote:
>If it's that uniform I think you can just use __cmp__:

Good point -- I had somehow picked up the mistaken idea that __cmp__ was
depreciated in favour of rich comparisons.
If you inherit from a base class that implements rich comparisons, you have
to override all those methods, else your __cmp__ won't be called at all.
Sometimes it may be enough to implement __cmp__ and make all others call it.

--
Gabriel Genellina

Jan 14 '07 #11
On 2007-01-13, Steven D'Aprano <st***@REMOVE.T HIS.cybersource .com.auwrote:
I'm writing a class that implements rich comparisons, and I find myself
writing a lot of very similar code. If the calculation is short and
simple, I do something like this:
class Parrot:
def __eq__(self, other):
return self.plumage() == other.plumage()
def __ne__(self, other):
return self.plumage() != other.plumage()
def __lt__(self, other):
return self.plumage() < other.plumage()
def __gt__(self, other):
return self.plumage() other.plumage()
def __le__(self, other):
return self.plumage() <= other.plumage()
def __ge__(self, other):
return self.plumage() >= other.plumage()
Well one thing you could do is write the following class:

Comparators = SomeEnumWith("e q, ne, lt, gt, ge, le, ge")

class GeneralComparat or:
def __eq__(self, other):
return Comparators.eq in self.__compare_ _(self, other)
def __ne__(self, other):
return Comparators.ne in self.__compare_ _(self, other)
def __lt__(self, other):
return Comparators.lt in self.__compare_ _(self, other)
def __le__(self, other):
return Comparators.le in self.__compare_ _(self, other)
def __gt__(self, other):
return Comparators.gt in self.__compare_ _(self, other)
def __ge__(self, other):
return Comparators.ge in self.__compare_ _(self, other)
Then write your Parrot class as follows:

class Parrot (GeneralCompara tor):
def __compare__(sel f, other):
return a set which defines which comparisons should return true.

--
Antoon Pardon
Jan 15 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2067
by: Simon Burton | last post by:
In today's experiment, I was wondering if I could make the comparison operators (<,<=,>=,>) work on classes (types) according to inheritance. The idea is, for example, classes lower in the class hierarchy would be less than (more specialized) than classes they inherit from. class A(object): pass class B(A):
3
1369
by: Stian Søiland | last post by:
Could anyone explain to me why this does not work as intended? >>> class Oldstyle: .... pass .... >>> old = Oldstyle() >>> old == 1 False >>> old.__eq__ = lambda x: True >>> old == 1
4
1530
by: John Hunter | last post by:
In matplotlib, a plotting library with an OO API and a matlab-like procedural interface, I have a lot of functions defined in the matlab interface module that wrap similarly named class methods defined in the Axes class of the axes module. Eg, the Axes class defines a plot method and the matlab interface defines a plot function that gets the current Axes instance, calls the plot method on that instance, and does some error handling. Here...
4
2275
by: Dim | last post by:
I found that C# has some buggy ways to process string across methods. I have a class with on global string var and a method where i add / remove from this string Consider it a buffer... with some values and separators class { private string globalvar = ""; private void manipulate (whattodo ) //substring, join, etc....
0
2509
by: metaperl | last post by:
A Comparison of Python Class Objects and Init Files for Program Configuration ============================================================================= Terrence Brannon bauhaus@metaperl.com http://www.livingcosmos.org/Members/sundevil/python/articles/a-comparison-of-python-class-objects-and-init-files-for-program-configuration/view
0
2582
by: SvenMathijssen | last post by:
Hi, I've been wrestling with a problem for some time that ought to be fairly simple, but turns out to be very difficult for me to solve. Maybe someone here knows the answer. What I try to do is sort the records in a plain-text index file based on certain columns. The index file consists of records and fields within the records. The individual fields are separated by semicolons, the records by newlines. The index file is loaded into memory...
16
11135
by: Neil | last post by:
I posted a few days ago that it seems to me that the Access 2007 rich text feature does not support: a) full text justification; b) programmatic manipulation. I was hoping that someone might know one way or the other whether that was true or not, or could point me to an article or help text that would. What I have seen so far online and in Access 2007 help seems to confirm the above. But that (or at least (b)) seems incredible that it...
4
1382
by: Stef Mientki | last post by:
hello, I had a program that worked perfectly well. In this program modules were dynamically added, just by putting the file in a predefined directory. Now one of the interface mechanisms was to see if some parameter was changed in a an instance, by comparing the value from the instance with its previous value
0
1125
by: Gabriel Genellina | last post by:
En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman <ethan@stoneleaf.us> escribi�: If your objects obey the trichotomy law (an object MUST BE less than, greater than, or equal to another one, and there is no other possibility) then __cmp__ is enough, and easier to define than all the rich comparison operations. In other cases, __cmp__ is not suitable: by example, complex numbers can't define "greater than" ; you can only use "equal" or...
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10315
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10085
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6737
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5379
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.