Python冷知识008篇:__int__、__index__ 与 __float__,Python 数值转换的真实回退顺序
摘要 :如果让同一个对象同时实现 __int__ 和 __index__,让它们返回不同的值,那么 int(x) 会采用 __int__ 的返回值,而 hex(x)、range(x)、切片和 operator.index(x) 只采用 __index__ 的返回值。一个对象对应两套整数协议:__int__ 允许有损转换,__index__ 表示对象本身就是整数。本文通过几行代码说明这两套协议的分工、回退顺序和返回值契约,以及 float() 在其中不对称的位置------它在缺少 __float__ 时会回退到 __index__,却从不看 __int__。
环境:CPython 3.12.3
一、int() 的真实顺序:__int__ → __index__ → __trunc__
先定义几个只实现单一协议的对象:
python
class OnlyInt:
def __int__(self):
return 1
class OnlyIndex:
def __index__(self):
return 2
class OnlyTrunc:
def __trunc__(self):
return 3
class TruncIndex:
def __trunc__(self):
return 3
def __index__(self):
return 4
实测结果:
text
int(OnlyInt()) = 1
int(OnlyIndex()) = 2
int(OnlyTrunc()) = 3 # DeprecationWarning
int(TruncIndex()) = 4
也就是说,int(x) 的实际顺序是:
__int____index____trunc__
第三级在 Python 3.12 中仍然可用,但已经弃用,会发出:
text
DeprecationWarning: The delegation of int() to __trunc__ is deprecated.
TruncIndex 同时实现了 __trunc__ 和 __index__,结果为 4,说明 __index__ 优先于 __trunc__。新代码不应依赖 __trunc__ 这一级回退。
二、float() 看的是 __float__ 和 __index__,不是 __int__
这是原文最容易写反的地方:float() 在没有 __float__ 时会回退到 __index__。它不看的是 __int__。
python
class OnlyInt:
def __int__(self):
return 1
class IndexFive:
def __index__(self):
return 5
class Weird:
def __int__(self):
return 1
def __index__(self):
return 2
class HasFloat:
def __float__(self):
return 1.5
def __index__(self):
return 2
实测:
text
float(IndexFive()) = 5.0
float(Weird()) = 2.0
float(OnlyInt()) → TypeError: float() argument must be a string or a real number, not 'OnlyInt'
float(HasFloat()) = 1.5
逐条解释:
IndexFive只实现了__index__,float()仍然返回5.0,证明float()会使用__index__。Weird同时有__int__ = 1和__index__ = 2,结果取2.0,说明float()不看__int__。OnlyInt只有__int__,float()直接报TypeError。HasFloat同时有__float__和__index__,结果为1.5,说明__float__优先于__index__。
因此 float() 的转换链应写成:
text
__float__ → __index__
而不是:
text
__float__ → __int__
"对象能转成 int"并不等于"对象能转成 float"。正确的例子是 OnlyInt:它能通过 int(OnlyInt()) 得到 1,但 float(OnlyInt()) 会失败。反过来,只实现 __index__ 的对象 IndexFive 两者都能转。
三、hex()、oct()、bin() 和 operator.index() 只认 __index__
__index__ 是 Python 里真正的"整数协议"。很多接受整数参数的内置操作只调用它,不会调用 __int__。
python
import operator
class OnlyInt:
def __int__(self):
return 1
class IndexTwo:
def __index__(self):
return 2
实测:
text
int(IndexTwo()) = 2
hex(IndexTwo()) = '0x2'
operator.index(IndexTwo()) = 2
hex(OnlyInt()) → TypeError: 'OnlyInt' object cannot be interpreted as an integer
operator.index(OnlyInt()) → TypeError: 'OnlyInt' object cannot be interpreted as an integer
这就是 __int__ 和 __index__ 的关键区别:
__int__主要服务于int(x)。__index__服务于整数下标、位运算、hex()、oct()、bin()、operator.index()等场景。
如果一个对象要"像整数一样"参与这些操作,应该实现 __index__,而不是只实现 __int__。
四、NotImplemented 不会触发回退
__int__ 返回 NotImplemented 时,int() 不会继续尝试 __index__,而是直接抛错。
python
class NoFallback:
def __int__(self):
return NotImplemented
def __index__(self):
return 7
实测:
text
int(NoFallback()) → TypeError: __int__ returned non-int (type NotImplementedType)
虽然这个对象实现了 __index__,但 __int__ 已经存在并返回了 NotImplemented,int() 不会把它当成"未实现"然后回退。
五、__int__ 返回 bool 会触发弃用警告
bool 是 int 的严格子类。__int__ 返回 bool 在 3.12 中仍可用,但会发出 DeprecationWarning:
python
import warnings
class BoolInt:
def __int__(self):
return True
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
int(BoolInt())
print(w[0].category.__name__, w[0].message)
输出:
text
DeprecationWarning __int__ returned non-int (type bool). The ability to return an instance of a strict subclass of int is deprecated, and may be removed in a future version of Python.
写 __int__ 时应返回真正的 int,不要返回 bool 或其他 int 的严格子类。
六、汇总表
| 操作 | 优先使用 | 回退顺序 | 不会使用 |
|---|---|---|---|
int(x) |
__int__ |
__int__ → __index__ → __trunc__(3.12 已弃用) |
--- |
float(x) |
__float__ |
__float__ → __index__ |
__int__ |
hex(x) / oct(x) / bin(x) |
__index__ |
仅 __index__ |
__int__ |
operator.index(x) |
__index__ |
仅 __index__ |
__int__ |
七、结论
int()的顺序是__int__→__index__→__trunc__,最后一级已经弃用。float()的顺序是__float__→__index__,它不看__int__。- 只实现
__index__的对象可以同时通过int()和float()转换;只实现__int__的对象不能通过float()转换。 hex()、oct()、bin()和operator.index()只认__index__。__int__返回NotImplemented不会回退到__index__,而是直接抛出TypeError。__int__返回bool会触发弃用警告,应返回真正的int。
全部代码块已整体复跑通过,每条注释输出都与实测逐字一致。以下是修订稿。
八、同一个对象,两个答案
python
import operator
class Weird:
def __int__(self):
return 1
def __index__(self):
return 2
x = Weird()
print(int(x)) # 1
print(hex(x)) # 0x2
print(range(x)) # range(0, 2)
print([10, 20, 30, 40][x]) # 30
print(operator.index(x)) # 2
同一个 x,int(x) 得到 1,hex(x) 却得到 0x2。这不是实现错误,因为这两个内置函数询问的是两个不同的问题:
int(x)问的是"能不能把你转换成 int";hex(x)问的是"你是不是一个整数"。
Weird 对前一个问题回答 1,对后一个问题回答 2,因此两个函数各自取到了它想要的答案。
九、两套整数协议
Python 里与"整数"相关的两个特殊方法,职责并不相同:
__int__表示一种转换,可以把对象变成 int。转换允许有损,比如int(3.9)得到 3。__index__表示对象本身就是整数。返回值会被直接当作下标、计数或范围边界使用,调用方默认它是精确的。显式获取这个值的入口是operator.index()。
__index__ 由 PEP 357 引入,目的就是让切片这类位置可以要求一个真正的整数,而不是接受 __int__ 的截断结果。
不同操作会调用这两个方法中的哪一个,可以整理成一张表:
| 操作 | 使用的特殊方法 | 含义 |
|---|---|---|
int(x) |
优先 __int__,缺失时用 __index__(3.12 还保留已弃用的 __trunc__) |
转换,允许有损 |
float(x) |
优先 __float__,缺失时用 __index__,不看 __int__ |
浮点转换 |
hex(x)、bin(x)、oct(x) |
__index__ |
生成整数表示 |
range(x)、lst[x]、[0] * x |
__index__ |
需要整数下标或计数 |
operator.index(x) |
__index__ |
明确要求整数 |
因此,当一个对象同时实现这两个方法、而它们的返回值又不一致时,出现"同一个对象两个数"就是必然结果。
int() 的第三个入口值得单独一提。只实现 __trunc__ 的对象也能被 int() 接受,但这条路径在 3.12 已被标记为弃用:
python
class OnlyTrunc:
def __trunc__(self):
return 3
print(int(OnlyTrunc())) # 3
# DeprecationWarning: The delegation of int() to __trunc__ is deprecated.
这一层的优先级低于 __index__:当一个对象同时提供 __trunc__ 和 __index__ 时,int() 取的是后者。所以完整的顺序是 __int__ → __index__ → __trunc__,最后一级正在退出历史舞台。
十、只实现一个方法会怎样
先看只有 __int__ 的对象:
python
class OnlyInt:
def __int__(self):
return 5
y = OnlyInt()
print(int(y)) # 5
for label, fn in [("hex", hex), ("range", range)]:
try:
fn(y)
except TypeError as e:
print(label, "->", e)
try:
[10, 20, 30, 40][y]
except TypeError as e:
print("index ->", e)
try:
[10, 20, 30, 40][y:2]
except TypeError as e:
print("slice ->", e)
输出:
text
5
hex -> 'OnlyInt' object cannot be interpreted as an integer
range -> 'OnlyInt' object cannot be interpreted as an integer
index -> list indices must be integers or slices, not OnlyInt
slice -> slice indices must be integers or None or have an __index__ method
int(y) 能正常工作,因为 int() 会调用 __int__。但 hex()、range() 和切片不接受这种有损转换,它们只寻找 __index__,于是各自给出自己的报错------下标和切片连错误信息都不一样。
再看只有 __index__ 的对象:
python
class OnlyIndex:
def __index__(self):
return 2
z = OnlyIndex()
print(int(z)) # 2
print(hex(z)) # 0x2
print(range(z)) # range(0, 2)
print([10, 20, 30, 40][z]) # 30
print([0] * z) # [0, 0]
结果全部可用。在 3.12 上,int() 找不到 __int__ 时会回退到 __index__,因此只实现后者反而更通用。
十一、float() 走的是第三条路
int() 能接受 float,因为 float 提供的是有损的整数转换;但 float 不是整数,operator.index() 会直接拒绝它。而 float() 又是另一个方向------它不接受"转换",只接受"是整数"这个声明:
python
import operator
print(int(3.9)) # 3
try:
operator.index(3.9)
except TypeError as e:
print(e) # 'float' object cannot be interpreted as an integer
class OnlyInt: # 与第三节相同:只有 __int__
def __int__(self):
return 5
try:
float(OnlyInt())
except TypeError as e:
print(e) # float() argument must be a string or a real number, not 'OnlyInt'
class IndexFive: # 只有 __index__,返回值同样是 5
def __index__(self):
return 5
print(float(IndexFive())) # 5.0
同样表示 5 的两个对象,命运完全不同:float(IndexFive()) 得到 5.0,float(OnlyInt()) 直接报错。原因是 float() 在找不到 __float__ 时会回退到 __index__,但对 __int__ 视而不见。
回到第一节的 Weird,这一点更直观。它同步实现了两个方法、返回值分别是 1 和 2,而 float(Weird()) 得到 2.0 ------float() 取的是 __index__ 的 2,不是 __int__ 的 1。
所以三条转换路径的入口并不相同,回退规则也不对称:
int()使用__int__,缺失时回退到__index__;- 下标、计数和整数表示使用
__index__; float()使用__float__,缺失时同样回退到__index__,但从不看__int__。
一个对象"能转成 int"不代表它"是整数",也不代表它"能转成 float"。float() 认可的是 __index__ 这种"我就是整数"的声明,而不是 __int__ 这种"我可以变成一个整数"的承诺------这也是为什么 int(3.9) 能成功,而 float(OnlyInt()) 会失败。
十二、返回值契约
两个方法都要求返回 int,而且都有各自的报错:
python
class BadInt:
def __int__(self):
return "x"
class BadIndex:
def __index__(self):
return "x"
for obj in (BadInt(), BadIndex()):
try:
int(obj)
except TypeError as e:
print(type(obj).__name__, "->", e)
输出:
text
BadInt -> __int__ returned non-int (type str)
BadIndex -> __index__ returned non-int (type str)
另一个容易忽略的边界情况是 NotImplemented:
python
class NoFallback:
def __int__(self):
return NotImplemented
def __index__(self):
return 7
try:
print(int(NoFallback()))
except TypeError as e:
print(e) # __int__ returned non-int (type NotImplementedType)
int() 发现对象有 __int__,就会一直用它;即使它返回 NotImplemented,也不会退回去尝试 __index__。这里 __index__ 虽然返回了 7,也没有被调用。
两个方法都要求返回 int。返回 bool 目前仍然可用------bool 是 int 的严格子类,结果会被转换为 1------但 CPython 3.12 会发出 DeprecationWarning,提示这种返回严格子类的行为未来可能被移除。实测中 int()、hex()、operator.index() 三条路径都会触发这条警告,警告原文明确指向"strict subclass of int"。
十三、实践建议
如果自己的类型本质上是一个索引或计数,就实现 __index__。这样 operator.index()、切片、range() 都能用;在 3.12 上,int() 和 float() 也都会回退到它。
如果自己的类型只是"可以转换成 int",比如某种带小数的度量,就实现 __int__,不要为了让它能当列表下标而去补 __index__。后者会让调用方误以为这个对象是无损整数,从而把截断行为隐藏起来。
如果两个方法都实现,就要接受它们的返回值可能被不同操作分别读取:int() 走 __int__,所有需要整数本身的位置(包括 float() 的回退)走 __index__。让两者返回不同的值可以制造出文章开头那种现象,但没有实际收益。
最后记住两个入口的语义差别:operator.index(x) 是在说"给我一个确定的整数",int(x) 是在说"尽量把 x 转成整数"。int(3.9) 能成功,而 [1, 2, 3][3.9] 会报错,原因就是下半句:涉及下标的位置不接受静默截断。