The fraction object does not have __int__, but int (Fraction (...)) still works

In Python, when you have an object, you can convert it to an integer using a function int.

For example, int(1.3)will return 1. This works internally using the __int__object's magic method , in this particular case float.__int__.

In Python, Fractionobjects can be used to build exact fractions.

from fractions import Fraction
x = Fraction(4, 3)

Fractionthere are not enough objects __int__, but you can still call int()on them and get a reasonable integer. I was wondering how this was possible without defining a method __int__.

In [38]: x = Fraction(4, 3)

In [39]: int(x)
Out[39]: 1
+4
source share
1 answer

The method used __trunc__.

>>> class X(object):
    def __trunc__(self):
        return 2.


>>> int(X())
2

__float__

>>> class X(object):
    def __float__(self):
        return 2.

>>> int(X())
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    int(X())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'X'

CPython , __trunc__.

+8

All Articles