如何使用slots
使用__slot__
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__
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不用字典方式来分配存储空间;