python在类中使用__slot__属性

在类中定义__slot__属性来限制实例的属性字段,在创建大量对象的场合可以减少内存占用。

创建大量对象是内存占用对比:

  1. 类中不使用__slot__
class MySlot:def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

@profile()
def main():
    myObj_list = list()
    for i in range(50000):
        myObj = MySlot(i, i, i)
        myObj_list.append(myObj)

执行结果:

Line # Mem usage Increment Line Contents
================================================
401 39.7 MiB 39.7 MiB @profile()
402 def main():
403 39.7 MiB 0.0 MiB myObj_list = list()
404 49.9 MiB 0.0 MiB for i in range(50000):
405 49.9 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 49.9 MiB 0.4 MiB myObj_list.append(myObj)

占用内存约10M

  1. 类中使用__slot__
class MySlot:
    __slots__ = ('a', 'b', 'c')
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

@profile()
def main():
    myObj_list = list()
    for i in range(50000):
        myObj = MySlot(i, i, i)
        myObj_list.append(myObj)

执行结果:

Line # Mem usage Increment Line Contents
================================================
401 40.3 MiB 40.3 MiB @profile()
402 def main():
403 40.3 MiB 0.0 MiB myObj_list = list()
404 45.7 MiB 0.0 MiB for i in range(50000):
405 45.7 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 45.7 MiB 0.3 MiB myObj_list.append(myObj)

占用内存约5M

  1. 说明

  __slot__限制了属性值,添加__slot__元组之外的属性会报错!

  __slot__限制的是实例属性的添加,不显示类属性的添加!

猜你喜欢

转载自www.cnblogs.com/bryant24/p/11441151.html