getsizeof() 函数 returns Python 2 和 Python 3 中的不同输出

getsizeof() function returns different output in Python 2 and Python 3

小代码:

import sys

x = True

print(sys.getsizeof(x))

Python 2输出:

24

Python 3输出:

28

为什么 getsizeof() 的输出在 Python 2 和 Python 3 中的功能不同?

在 Python 2 和 Python 3 上,boolintTrue == 1 的子类。但是,在 Python 3 上,int 等效于 Python 2 long,并且它以任意精度表示形式存储整数。

在 Python 3 的构建中,您是 运行,该表示恰好比 int 表示在您的 Python 2 构建,很可能是由于 ob_size 字段存储了任意精度表示的长度。

如果这对您编写的程序真的很重要,那么您可能正在做一些非常疯狂的事情,and/or 滥用 getsizeof

对于内置类型,sys.getsizeof() returns 基本上是您正在使用的 Python 实现的 实现细节

这意味着,即使对于相同的 Python 版本,您可能会看到不同 implementations/platforms/builds 的不同尺寸...因此,您不能依赖关于具体的答案——更不用说期望它们保持不变了!

最后,请注意 sys.getsizeof() 不是运算符;它只是 sys 模块的一个函数。