[Edu-sig] Consistency question

Guido van Rossum guido at python.org
Wed Sep 24 20:18:04 EDT 2003

> My understanding is that int(5.0) actually triggers __int__ -- a method
> inherited by all floats.  
> When I go dir(5.0), I see __int__ listed, and I can go:
>  >>> 5.0 .__int__()
>  5
> So far so good.  
> But then I can also go int('123') and get back 123.  So why isn't __int__ a
> method of string objects?
>  >>> '123' .__int__()
> gets me an error, and dir('') doesn't show __int__ as being among string's
> methods.
> Why?
> I'd like to clear up this confusion because I'm writing some tutorial
> materials.  What I don't understand, I can't rightly explain.

int() special-cases various argument types.  It only calls __int__
when none of the special cases apply.  An argument of type str is a
special case (as is an argument of type unicode) because in that case,
and *only* that case, the optional second 'base' argument is accepted.

(If you really want to know more, RTSL. :-)

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Edu-sig mailing list