7-2 如何为创建大量实例节省内存
解决方案:
定义类的slots属性,它是用来声明实例属性名字的列表
有了slots之后对象就不可以再新添加属性 p1.x
dict
import sys
class Player(object):
def __init__(self,uid,name,status=0,level=1):
self.uid = uid
self.name = name
self.status = status
self.level = level
class Player2(object):
__slots__= ['uid','name','status','level']
def __init__(self,uid,name,status=0,level=1):
self.uid = uid
self.name = name
self.status = status
self.level = level
p1=Player('20014540','weihuap')
p2=Player2('20014541','weihuap')
print dir(p1)
print dir(p2)
print "the delta was %s"%(set(dir(p1))-set(dir(p2)))
print p1.__dict__
print sys.getsizeof(p1.__dict__)
print sys.getsizeof(p1)
print sys.getsizeof(p2)