Overloading comparison method (__cmp__)

Peer Griebel (griebel@eniac.uni-paderborn.de)
16 Feb 1995 15:24:54 +0100

Hi,

I'm just very new to python. But I think I will use it in the future.
To become familiar with python I started to port one of my programs.

I would like to implement a new class called Variable. A Variable should
have knowledge about an intervall of values which can be assigned to
the variable. To set the borders of the intervall I would like to use
the comparison methods <= and >=. To assign a new value to a Variable
I want to use ==. My code currently looks like this:

NINF = -1E10
PINF = -NINF

class Variable:
LowerBound = NINF
UpperBound = PINF
Value = 0.0
def __init__( self, n = "None" ) :
self.Name = n
def __repr__(self):
return self.Name+"("+str(self.Value)+"["+ \
str(self.LowerBound)+","+ \
str(self.UpperBound)+"])"
__str__ = __repr__
def SetUpperBound( self, v ) :
if( v < self.LowerBound ):
raise ValueError, 'New Upper Bound < LowerBound'
if( v < self.UpperBound ):
self.UpperBound = v
def SetLowerBound( self, v ) :
if( v > self.UpperBound ):
raise ValueError, 'New Lower Bound > UpperBound'
if( v > self.LowerBound ):
self.LowerBound = v
def SetValue( self,v )
if( v < self.LowerBound ):
raise ValueError, 'New Value < LowerBound'
if( v > self.UpperBound ):
raise ValueError, 'New Value > UpperBound'
self.Value = v

I would like to add methods called '<=' which stands for SetUpperBound and
a method called '>=' which does SetLowerBound. An additional method called
'==' should call SetValue.

Python does not allow to do this, because it only offers the method __cmp__
to be overlayd. It would be nice if this method could query the original
type of comparison requested. It would be still better if __cmp__ could be
replaced by different methods, one for each of the comparsion types <=, <,
==, >, >=, !=.

Or is there anything I have overlooked?

Thank you for your help!

connection reset by
Peer

-----------------------------------------------------------------------------
Dipl.Inform. Universitaet-GH Paderborn dying is easy
Peer Griebel Fachbereich 17 - Informatik it's living
Tel.: 05251-60-2076 D-33095 Paderborn that scares me
griebel@uni-paderborn.de Raum C2.305 (A. Lennox)
-----------------------------------------------------------------------------
<A HREF="http://www.uni-paderborn.de/fachbereich/AG/szwillus/griebel.html">
P. Griebel</A>.