ITPub博客

首页 > IT职业 > IT图书 > Python中__slots__的禁用实例

Python中__slots__的禁用实例

IT图书 作者:hu261 时间:2021-09-11 09:57:59 0 删除 编辑

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电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3112/viewspace-2830401/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    77
  • 访问量
    760