当前位置: 首页 > 图灵资讯 > 行业资讯> Python中__slots__的禁用实例

Python中__slots__的禁用实例

发布时间:2024-08-21 22:26:22

1、说明

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

2、实例

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

classTest:
__slots__=('a','b')

def__init__(self,a,b):
self.a=a
self.b=b
>>>t=Test(1,2)
>>>t.__dict__
AttributeError:'Test'objecthasnoattribute'__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电脑。

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09