【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
来源:互联网 发布:数据库添加语句 编辑:程序博客网 时间:2024/04/27 01:28
如何使用slots
- 使用__slot__
# -*- coding:utf-8 -*-# only for Python 3.ximport ipython_memory_usage.ipython_memory_usage as imuclass ThisClass(object): def __init__(self, name, address): self.name = name self.address = addressimu.start_watching_memory()num = 1024*256x = [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 = addressnum = 1024*256x = [ThisClass(1,1) for i in range(num)]
什么是slots
使用__slot__可以保证Python运用固定集合来分配存储空间;
为何使用slots
在通常情况下,在对象创建时使用一个字典来保存一个对象的实例属性;
这个字典可以在运行时任意扩充,对于属性不可知的对象自然很有用处;
对于属性可知的对象,这会造成内存资源的浪费。
此外,创建大量的对象时,也会消耗很多的内存。
使用__slot__可以保证Python不用字典方式来分配存储空间;
阅读全文
0 0
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识协程,你需要知道的事
- 【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识推导式,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
- Git 和 Github 使用教程
- css
- codeforces830A (二分|DP)
- Java学习笔记 02
- 测试
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 数据库事务的四大特性以及事务的隔离级别
- unicode gbk 转换函数
- Node.js中间件和spring boot配合使用
- Firebase-config 在android中的使用
- java.lang.ClassCastException: class com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$
- java集合框架的讲解
- oracle编程基础语法
- Unity3d 局域网小游戏DEMO学习