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

 ̄綄美尐妖づ 提交于 2019-12-01 19:43:57
User

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.

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