【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
2017-07-16 10:54
836 查看
如何使用slots
使用__slot__# -*- coding:utf-8 -*- # only for Python 3.x import ipython_memory_usage.ipython_memory_usage as imu class ThisClass(object): def __init__(self, name, address): self.name = name self.address = address imu.start_watching_memory() num = 1024*256 x = [ThisClass(1,1) for i in range(num)]
-------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-9-570d1600168e> in <module>() 1 ----> 2 import ipython_memory_usage.ipython_memory_usage as imu 3 4 class ThisClass(object): 5 def __init__(self, name, address): ImportError: No module named ipython_memory_usage.ipython_memory_usage
使用__slot__
# -*- coding:utf-8 -*- from slots import * class ThisClass(object): __slot__ = ['name', 'address'] def __init__(self, name, address): self.name = name self.address = address num = 1024*256 x = [ThisClass(1,1) for i in range(num)]
什么是slots
使用__slot__可以保证Python运用固定集合来分配存储空间;为何使用slots
在通常情况下,在对象创建时使用一个字典来保存一个对象的实例属性;这个字典可以在运行时任意扩充,对于属性不可知的对象自然很有用处;
对于属性可知的对象,这会造成内存资源的浪费。
此外,创建大量的对象时,也会消耗很多的内存。
使用__slot__可以保证Python不用字典方式来分配存储空间;
相关文章推荐
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
- 【脚本语言系列】关于Python基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识推导式,你需要知道的事
- 【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事
- 【脚本语言系列】关于Python基础知识协程,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象变动,你知道的事