subclass of integers

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Sep 14 23:27:09 EDT 2007


En Fri, 14 Sep 2007 20:16:36 -0300, Dan Bishop <danb_83 at yahoo.com>  
escribi�:

> On Sep 14, 9:30 am, Mark Morss <mfmo... at aep.com> wrote:
>> I would like to construct a class that includes both the integers and
>> None.  I desire that if x and y are elements of this class, and both
>> are integers, then arithmetic operations between them, such as x+y,
>> return the same result as integer addition.  However if either x or y
>> is None, these operations return None.
>
> Rather than subclassing int, why not just make a singleton NaN object
> with overloaded arithmetic operators that all return NaN?

Like this:

class _NaN(object):

     __instance = None

     def __new__(cls):
         if cls.__instance is None:
             cls.__instance = super(_NaN, cls).__new__(cls)
         return cls.__instance

     __repr__ = __str__ = lambda self: 'NaN'

     def unop(self): return self
     def binop(self, other): return self
     def terop(self, other, unused=None): return self
     def false2(self, other): return False
     def true2(self, other): return True
     def notimpl(self): return NotImplemented

     __abs__ = __invert__ = __neg__ = __pos__ = unop
     __add__ = __and__ = __div__ = __divmod__ = __floordiv__ = __lshift__ =  
__mod__ = __mul__ = __rshift__ = __or__ = __sub__ = __truediv__ = __xor__  
= binop
     __radd__ = __rand__ = __rdiv__ = __rdivmod__ = __rfloordiv__ =  
__rlshift__ = __rmod__ = __rmul__ = __rpow__ = __rrshift__ = __ror__ =  
__rsub__ = __rtruediv__ = __rxor__ = binop
     __pow__ = terop
     __lt__ = __le__ = __eq__ = __gt__ = __ge__ = false2
     __ne__ = true2

     del unop, binop, terop, false2, true2, notimpl

NaN = _NaN()

def test():
     assert NaN + 1 is NaN
     assert 1 & NaN is NaN
     assert NaN * NaN is NaN

     assert abs(NaN) is NaN
     assert str(NaN)=="NaN"
     assert repr(NaN)=="NaN"

     assert not (NaN==NaN)
     assert (NaN!=NaN)
     assert not (NaN>NaN)
     assert not (NaN<NaN)
     assert not (NaN>=NaN)
     assert not (NaN<=NaN)

     assert not (NaN==1)
     assert (NaN!=1)
     assert not (NaN>1)
     assert not (NaN<1)
     assert not (NaN>=1)
     assert not (NaN<=1)

     assert not (1==NaN)
     assert (1!=NaN)
     assert not (1>NaN)
     assert not (1<NaN)
     assert not (1>=NaN)
     assert not (1<=NaN)

     assert cmp(NaN, 1)!=0
     assert cmp(1, NaN)!=0
     #assert cmp(NaN, NaN)!=0

     assert NaN is _NaN()
     assert NaN is type(NaN)()

test()



-- 
Gabriel Genellina




More information about the Python-list mailing list