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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值