python-24-如何派生类内置不可变类型并修改其实例化行为?如何为创建大量实例节省内存?

来源:互联网 发布:淘宝二手手机可信吗 编辑:程序博客网 时间:2024/05/16 04:49

image

image

# 创建一个插口IntTuple,包含内置插口tuple,行为一致.tuple是一个不可变对象,所以我们不能从self来删除一些数据class IntTuple(tuple):    #__new__的参数是一个类对象,此时我们来修改他    def __new__(cls,iterable):        # 使用生成器对象        g = (x for x in iterable if isinstance(x,int) and x > 0)        return super(IntTuple,cls).__new__(cls,g)    def __init__(self,iterable):        # py2需要在__init__里面传参        print(self) #此时已经创建好了        super(IntTuple,self).__init__()t = IntTuple([1,-1,'abc',6,['x','y'],3])print(t)
image
image
image
from  e import Player,Player2
p1 = Player(‘0001’,’Jim’)
p2 = Player2(‘0001’,’Jim’)
如果p1比p2使用的内存多的话,那么一定是多了某些属性
dir(p1)

image

dir(p2)

image

这样看有些麻烦,我们可以这样:

set(dir(p1)) – set(dir(p2))

image

__dict__是一个字典,实例动态绑定属性的字典,属性就是字典里的一项

image

image

当然,既然有动态添加,我们也可以动态解除

image

动态绑定属性的特性,是以牺牲内存为代价的

我们可以import sys模块来监测

image

使用__slots__来解除动态绑定,也就没有了__dict__属性了

image

0 0