subclass of integers

Mark Morss mfmorss at aep.com
Fri Sep 14 10:30:01 EDT 2007


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.

It's simple enough to construct a subclass of integers that behave in
this way:

class Nint(int):
    def __add__(self,other):
        if (other != None):
            return self+other
        else:
            return None
    def __radd__(self,other):
        if (other != None):
            return other+self
        else:
            return None
    #...and so forth

However I have not been able to figure out how to make it so that
None, as well as an integer, could be an element of my class.  My
preliminary impression is that I have to override int.__new__; but I
am uncertain how to do that and have been unable to find anything on
the web explaining that.  Indeed I haven't been able to find much
about __new__ at all.  Overriding this method of built-in classes
seems to be quite unusual.

I would very much appreciate anyone's help.




More information about the Python-list mailing list