[Python-Dev] boxing and unboxing data types

Antoine Pitrou solipsis at pitrou.net
Mon Mar 9 09:45:27 CET 2015


On Mon, 9 Mar 2015 15:12:44 +1100
Steven D'Aprano <steve at pearwood.info> wrote:
> 
> My summary is as follows:
> 
> __int__ is used as the special method for int(), and it should coerce 
> the object to an integer. This may be lossy e.g. int(2.999) --> 2 or may 
> involve a conversion from a non-numeric type to integer e.g. int("2").

Your example is misleading. Strings don't have an __int__:

>>> s = "3"
>>> s.__int__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__int__'

Only int-compatible or int-coercible types (e.g. float, Decimal) should
have an __int__ method.

Regards

Antoine.




More information about the Python-Dev mailing list