Extention to the integer class.
Quinn Dunkan
quinn at triskaideka.ugcs.caltech.edu
Mon Mar 13 16:05:58 EST 2000
On Mon, 13 Mar 2000 18:25:05 +0100 (CET), Gregoire Welraeds <greg at perceval.be>
wrote:
>In reply to the message of Anthony J Wilkinson sent on Mar 14 (see below) :
>
>> Alternatively you could use a __call__ method:
>> def __call__(self):
>> return self.__val
>
>This works great. It also avoid to implement __cmp__() since i can do:
>while i() < 2:
> ...
>
>Thanks too :)
Also note that you can use __coerce__:
class Int:
def __init__(self, val):
self.__val = val
def __int__(self):
return self.__val
def inc(self):
return Int(self + 1)
def dec(self):
return Int(self - 1)
def __repr__(self):
return repr(self.__val)
def __coerce__(self, other):
return (int(self), other)
Your original one mutated itself, but hopefully you didn't really mean that :)
And this one should probably have __add__ etc.
Of course, lists and tuples still won't attempt to coerce their index to an
int, but then you could do:
class CoerceList(UserList.UserList):
def __getitem__(self, i):
return self.data[coerce(i, 0)[0]]
... etc for setitem, has_key ...
But this seems like a lot of work just to add two methods (and it's gonna be
slow if you use it a lot). Everyone knows what i = i + 1 means, and it's not
that hard to type. On the other hand, IMHO it's a problem with python that
you can't subclass built-in types.
But __coerce__ is tons of fun. If you ever find yourself bored, go through
all your code and make it use __coerce__ extensively. After that, you'll
never have a dull moment again.
More information about the Python-list
mailing list