为什么在我的课堂上使用__slots__没有大小差异?

时间:2016-05-18 06:11:08

标签: python python-3.x

我最近向朋友解释了<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" onchange="readURL(this)" multiple/> <div class='test'></div>的用法。我想向他演示结果并使用以下代码:

__slots__

Python 3控制台上的输出是:

import sys


class Foo:
    __slots__ = 'a', 'b'

    def __init__(self, a, b):
        self.a = a
        self.b = b


class Bar:
    def __init__(self, a, b):
        self.a = a
        self.b = b


a = Foo(10, 20)
b = Bar(10, 20)

print(sys.getsizeof(a))
print(sys.getsizeof(b))

Python 2的输出是:

 56
 56

为什么尺寸没有差异?

2 个答案:

答案 0 :(得分:2)

对于Python2,您需要继承object以激活__slots__机器

问题在于你要比较苹果和橘子。

sys.getsizeof只是一个很小的尺寸,即。它不会计算所有内部物体的大小。

对于__slots__版本,您会看到它与插槽数量成正比

对于普通对象,您应该查看实例__dict__的大小以进行合理的比较。

另一种方法是分配几百万个这些对象,并查看操作系统报告的内存量。

答案 1 :(得分:1)

John La Rooy的观察结果是正确的,sys.getsizeof很浅,因此没有给出正确的结果。使用pympler asizeof模块,您可以看到有不同的答案:

from pympler import asizeof

class Foo:
    __slots__ = 'a', 'b'

    def __init__(self, a, b):
        self.a = a
        self.b = b


class Bar:
    def __init__(self, a, b):
        self.a = a
        self.b = b


x = Foo(10, 20)
y = Bar(10, 20)

print(asizeof.asizeof(x))
print(asizeof.asizeof(y))

运行:

python3 test.py

给出:

192
328