[Tutor] Inherit from int?

Marilyn Davis marilyn at deliberate.com
Sun May 13 15:58:14 CEST 2007


Thank you everyone.  I, indeed, found it in your book, Wes, after I
knew it was something extra special.

The explanations here are great!

Thank you everyone.

Marilyn



On Sun, 13 May 2007, wesley chun wrote:

> > I'm stumped.  This silly bit of code doesn't work.  I expect the
> > output to be 8, not 18.  What am I missing?
> >
> > class Under10(int):
> >     def __init__(self, number):
> >         number %= 10
> >         int.__init__(self, number)
> 
> marilyn,
> 
> i agree with most of the earlier replies... you need to use __new__()
> instead of __init__() in order to "tweak" the original value before
> the instance of the immutable object is created. once it's "frozen,"
> you're stuck.  note that __new__() is a class method, so you'll need a
> variable for the class (instead of self for the instance).
> 
> also recall that __init__() is (the 1st method) called *after* an
> instance has been created, which for you, would be too late.  in
> practice, i don't think __init__() is ever used for deriving from
> immutable types.  does anyone have a counterexample?
> 
> (since i know you've been reading Core Python, you can take a look at
> my example of subclassing an immutable type on p.552.)  :-)
> 
> cheers,
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>     http://corepython.com
> 
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
> 

-- 




More information about the Tutor mailing list