Subclassing int

Steve Holden steve at holdenweb.com
Tue Jul 24 03:16:58 CEST 2007


G wrote:
> Hi,
> 
>     I am trying to subclass int to allow a constructor to accept None. I 
> am trying the following
> 
> class INT(int):
>     def __init__(self, x):
>         if x is  None:
>             return None
>         else:
>             int.__init__(x)
> 
> b = INT(x=None)
> 
> When i run the previous code i get the following error:
>  b = INT(x=None)
> TypeError: int() argument must be a string or a number, not 'NoneType'.
> 
> Do you guys know why the if statement is not evaluated?
> 
> Thanks for your help
> 
Probably because you need to override the __new__() method rather than 
the __init__() method:

 >>> class INT(int):
...   def __new__(cls, arg=0):
...     if arg is None:
...       return None
...     else:
...       return int.__new__(cls, arg)
...
 >>> n = INT(3.2)
 >>> n
3
 >>> n = INT("42")
 >>> n
42
 >>> n = INT(None)
 >>> print n
None
 >>>

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list