Mark Morss a écrit : > 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.
You'll find documentation in the FineManual(tm): http://docs.python.org/ref/customization.html http://www.python.org/download/releases/2.2.3/descrintro/#__new__ and a possible (even if imperfect IMHO) example in my answer to Zentrader in the thread. Now would you be kind enough to satisfy my curiousity and explain your use case ?-) -- http://mail.python.org/mailman/listinfo/python-list