分数对象没有 __int__ 但 int(Fraction(...)) 仍然有效
Fraction object doesn't have __int__ but int(Fraction(...)) still works
在 Python 中,当您有一个对象时,您可以使用 int
函数将其转换为整数。
例如 int(1.3)
将 return 1
。这通过使用对象的 __int__
魔术方法在内部工作,在这种特殊情况下 float.__int__
.
在 Python Fraction
中,对象可用于构造精确分数。
from fractions import Fraction
x = Fraction(4, 3)
Fraction
对象缺少 __int__
方法,但您仍然可以对它们调用 int()
并得到一个合理的整数。我想知道在没有定义 __int__
方法的情况下这怎么可能。
In [38]: x = Fraction(4, 3)
In [39]: int(x)
Out[39]: 1
使用了__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'
The CPython source 在使用 __trunc__
时显示。
在 Python 中,当您有一个对象时,您可以使用 int
函数将其转换为整数。
例如 int(1.3)
将 return 1
。这通过使用对象的 __int__
魔术方法在内部工作,在这种特殊情况下 float.__int__
.
在 Python Fraction
中,对象可用于构造精确分数。
from fractions import Fraction
x = Fraction(4, 3)
Fraction
对象缺少 __int__
方法,但您仍然可以对它们调用 int()
并得到一个合理的整数。我想知道在没有定义 __int__
方法的情况下这怎么可能。
In [38]: x = Fraction(4, 3)
In [39]: int(x)
Out[39]: 1
使用了__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'
The CPython source 在使用 __trunc__
时显示。