• 技术文章 >Python技术 >Python基础教程

    Python中__slots__的禁用实例

    小妮浅浅小妮浅浅2021-05-26 09:25:00原创4635

    1、说明

    Python 的对象属性值都是采用字典存储的,当我们处理数成千上万甚至更多的实例时,内存消耗可能是一个问题,因为字典哈希表的实现,总是为每个实例创建了大量的内存。所以 Python 提供了一种 __slots__ 的方式来禁用实例使用 __dict__,以优化此问题。

    2、实例

    通过 __slots__ 来指定属性后,会将属性的存储从实例的 __dict__ 改为类的 __dict__ 中:

    class Test:
        __slots__ = ('a', 'b')
     
        def __init__(self, a, b):
            self.a = a
            self.b = b
    >>> t = Test(1, 2)
    >>> t.__dict__
    AttributeError: 'Test' object has no attribute '__dict__'
    >>> Test.__dict__
    mappingproxy({'__module__': '__main__',
                  '__slots__': ('a', 'b'),
                  '__init__': <function __main__.Test.__init__(self, a, b)>,
                  'a': <member 'a' of 'Test' objects>,
                  'b': <member 'b' of 'Test' objects>,
                  '__doc__': None})

    以上就是Python中__slots__的禁用实例,希望对大家有所帮助。更多Python学习推荐:python教学

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python __slots__
    品易云
    上一篇:Python对象属性的查找顺序 下一篇:Python描述器中__getattribute__调用

    相关文章推荐

    • Python3中类属性slots的常见疑问有哪些?• python中使用__slots__定义类属性• python中__dict__的实例属性存储• __dict__在python中的实例操作• Python对象属性的查找顺序

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网