[Tutor] HELP: subclass of int

Shidai Liu shidai.liu at gmail.com
Wed Mar 9 02:34:57 CET 2005


On Tue, 8 Mar 2005 17:15:00 -0800 (PST), Terry Carroll <carroll at tjc.com> wrote:
> On Tue, 8 Mar 2005, Shidai Liu wrote:
> 
> > I'll sum up a question as following:
> >
> > def int5():
> >     '''return 5'''
> >     return 5
> >
> > class my_int(int):
> >     def __init__(self):
> >         self.id = int5()
> >         int.__init__(self, self.id)  # FIXME: this line doesn't work
> >
> > the above code act like this:
> > >>> I = my_int()
> > >>> I
> > 0
> >
> > I want it to be like this:
> > >>> I = my_int()
> > >>> I
> > 5
> 
> You'll want to use the __new__ method, see
> http://www.python.org/2.2.3/descrintro.html#__new__

Great link. It explains so much.

> 
> Example:
> 
> >>> def int5():
> ...     '''return 5'''
> ...     return 5
> ...
> >>> class my_int(int):
> ...    def __new__(self):
> ...       return int.__new__(self, int5())
> ...
> >>> i = my_int()
> >>> i
> 5
> >>>
> 
> As someone else pointed out, you probably ought to call int.__init__ as
> well.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

It works. Thanks very much!

-- 
With best wishes!
Shidai


More information about the Tutor mailing list