Fraction object doesn't have __int__ but int(Fraction(…)) still works

☆樱花仙子☆ 提交于 2019-12-19 21:53:10

问题


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

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

In Python Fraction objects can be used to construct exact fractions.

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

Fraction objects lack an __int__ method, but you can still call int() on them and get a sensible integer back. I was wondering how this was possible with no __int__ method being defined.

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

In [39]: int(x)
Out[39]: 1

回答1:


The __trunc__ method is used.

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


>>> int(X())
2

__float__ does not work

>>> 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'

The CPython source shows when __trunc__ is used.



来源:https://stackoverflow.com/questions/30966227/fraction-object-doesnt-have-int-but-intfraction-still-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!