Python中__slots__的禁用实例

python学习网
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__的禁用实例,希望对大家有所帮助。


版权声明:本文为shannya_zhima原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。