首页 > 编程语言 > 详细

python在类中使用__slot__属性

时间:2019-09-01 10:45:06      阅读:106      评论:0      收藏:0      [点我收藏+]

在类中定义__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__限制的是实例属性的添加,不显示类属性的添加!

 

python在类中使用__slot__属性

原文:https://www.cnblogs.com/bryant24/p/11441151.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!