In [3]:
# modify instance action
class IntTuple(tuple):
def __init__(self, iterable):
print('in init', self, iterable)
def __new__(cls, iterable):
print('in new', cls.__name__, iterable)
g = (x for x in iterable if (isinstance(x, int) and x > 0))
return super(IntTuple, cls).__new__(cls, g)
In [4]:
t = IntTuple([1, -1, 'abc', ['x', 'y'], 6, 3])
t
Out[4]:
In [32]:
# Decrease the memory use of instances of a class
class Player0(object):
def __init__(self, uid, name, status=0, level=1):
self.uid = uid
self.name = name
self.stat = status
self.level = level
class Player1(object):
__slots__ = ['uid', 'name', 'stat', 'level']
def __init__(self, uid, name, status=0, level=1):
self.uid = uid
self.name = name
self.stat = status
self.level = level
In [33]:
p0 = Player0(uid='0000', name='Allen')
p1 = Player1(uid='0001', name='Bob')
In [35]:
set(dir(p0)) - set(dir(p1))
Out[35]:
In [36]:
p0.__dict__
Out[36]:
In [37]:
p0.x='123'
In [38]:
p0.__dict__
Out[38]:
In [39]:
p0.__dict__['y']=99
In [40]:
p0.y
Out[40]:
In [41]:
p0.__dict__
Out[41]:
In [42]:
del p0.__dict__['x']
In [43]:
p0.x
In [44]:
del p0.y
In [45]:
p0.y
In [46]:
p0.__dict__
Out[46]:
In [47]:
import sys
In [49]:
p1.x=2
In [53]:
sys.getsizeof(p0.__dict__)
Out[53]:
In [54]:
sys.getsizeof(p1.__slots__)
Out[54]: