Python的__slots__
用于减少实例的内存占用,这是通过将变量存储在"小型固定大小的数组中,很像元组或列表"来实现的。实例属性是可变的,但您无法添加其他属性。
另一方面,有一些数据类(从我收集到的(通过定义一些 dunders(等(来帮助创建类,并且被 PEP 557 描述为"具有默认值的可变命名元组"。
我知道它们的目的不同,您实际上可以使用它们。
dataclass
修饰器不会影响属性的存储或检索方式。内存消耗和属性访问时间的行为与在没有dataclass
的情况下编写类的行为完全相同。
使用__slots__
的类将比不使用__slots__
的类似类具有更少的内存消耗和稍快的属性访问(因为槽描述符节省了一些字典查找(,无论任何一个类是否使用dataclass
。下面是一个计时示例,显示dataclass
不会影响属性查找时间,而__slots__
会影响:
>>> import timeit
>>> import dataclasses
>>> @dataclasses.dataclass
... class Foo:
... a: int
... b: int
...
>>> class Bar:
... def __init__(self, a, b):
... self.a = a
... self.b = b
...
>>> foo = Foo(1, 2)
>>> bar = Bar(1, 2)
>>> timeit.timeit('foo.a', globals=globals())
0.08070236118510365
>>> timeit.timeit('bar.a', globals=globals())
0.07813134230673313
>>> timeit.timeit('foo.a', globals=globals(), number=10000000)
0.5699363159947097
>>> timeit.timeit('bar.a', globals=globals(), number=10000000)
0.5526750679127872
>>> @dataclasses.dataclass
... class FooSlots:
... __slots__ = ['a', 'b']
... a: int
... b: int
...
>>> class BarSlots:
... __slots__ = ['a', 'b']
... def __init__(self, a, b):
... self.a = a
... self.b = b
...
>>> fooslots = FooSlots(1, 2)
>>> barslots = BarSlots(1, 2)
>>> timeit.timeit('fooslots.a', globals=globals(), number=10000000)
0.46022069035097957
>>> timeit.timeit('barslots.a', globals=globals(), number=10000000)
0.4669580361805856