冷门Python知识点008篇:__int__、__index__与__float__,Python数值转换的真实回退顺序?

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) 的实际顺序是:

  1. __int__
  2. __index__
  3. __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__

七、结论

  1. int() 的顺序是 __int__ → __index__ → __trunc__,最后一级已经弃用。
  2. float() 的顺序是 __float__ → __index__,它不看 __int__。
  3. 只实现 __index__ 的对象可以同时通过 int() 和 float() 转换;只实现 __int__ 的对象不能通过 float() 转换。
  4. hex()、oct()、bin() 和 operator.index() 只认 __index__。
  5. __int__ 返回 NotImplemented 不会回退到 __index__,而是直接抛出 TypeError。
  6. __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] 会报错,原因就是下半句:涉及下标的位置不接受静默截断。

相关推荐
学长毕设9 分钟前
基于SpringBoot景区停车场预约管理系统-附源码
java·spring boot·后端
未秃头的程序猿11 分钟前
800 万条数据批量导出:我用线程池写出了 4 个 bug
java·后端
小小疯狐狸18 分钟前
我把CI从20分钟跑到5分钟
人工智能·后端
Sailing21 分钟前
🔥🔥还在用 any 硬撑通用层?Go 泛型再不补,下一轮重构你就接不住了
后端·面试·go
AAA修煤气灶刘哥25 分钟前
旧系统要升级,为什么第一步是把旧结果存一份?
java·后端·架构
喵个咪26 分钟前
RushWind Shop — 一笔订单的穿越:电商买路径上的每一道闸门
后端·微服务·rust
用户693717500138435 分钟前
当 Claude 开始反对蒸馏,我想起了那 700 万份盗版书籍
前端·后端·面试
FriendshipT35 分钟前
YOLOE Docker 部署实战:三模式推理、掩码输出与跨图视觉的完整实现
运维·人工智能·python·深度学习·docker·容器
tryCbest39 分钟前
Python 爬虫扩展篇(一):APP 抓包与 JS 逆向入门——从看见流量到读懂签名
javascript·爬虫·python