[Tutor] HELP: subclass of int

Terry Carroll carroll at tjc.com
Wed Mar 9 02:15:00 CET 2005


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__

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.



More information about the Tutor mailing list