Extention to the integer class.

Gregoire Welraeds greg at perceval.be
Tue Mar 14 04:16:58 EST 2000


In reply to the message of Quinn Dunkan sent on Mar 13 (see below) :

> Everyone knows what i = i + 1 means, and it's not that hard to type.  
No... but it is boring :)
Like I said the interest of my question was poor :)

--
Life is not fair
But the root password helps
--

Gregoire Welraeds
greg at perceval.be
Perceval Development team
-------------------------------------------------------------------------------
Perceval Technologies sa/nv	Tel: +32-2-6409194		
Rue Tenbosch, 9			Fax: +32-2-6403154		
B-1000 Brussels			general information:   info at perceval.net
BELGIUM				technical information: helpdesk at perceval.net
URL: http://www.perceval.be/
-------------------------------------------------------------------------------

On 13 Mar 2000, Quinn Dunkan wrote:

> Date: 13 Mar 2000 21:05:58 GMT
> From: Quinn Dunkan <quinn at triskaideka.ugcs.caltech.edu>
> To: python-list at python.org
> Newsgroups: comp.lang.python
> Subject: Re: Extention to the integer class.
> 
> 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.
> -- 
> http://www.python.org/mailman/listinfo/python-list
> 
> 





More information about the Python-list mailing list