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


in new IntTuple [1, -1, 'abc', ['x', 'y'], 6, 3]
in init (1, 6, 3) [1, -1, 'abc', ['x', 'y'], 6, 3]
Out[4]:
(1, 6, 3)

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]:
{'__dict__', '__weakref__'}

In [36]:
p0.__dict__


Out[36]:
{'level': 1, 'name': 'Allen', 'stat': 0, 'uid': '0000'}

In [37]:
p0.x='123'

In [38]:
p0.__dict__


Out[38]:
{'level': 1, 'name': 'Allen', 'stat': 0, 'uid': '0000', 'x': '123'}

In [39]:
p0.__dict__['y']=99

In [40]:
p0.y


Out[40]:
99

In [41]:
p0.__dict__


Out[41]:
{'level': 1, 'name': 'Allen', 'stat': 0, 'uid': '0000', 'x': '123', 'y': 99}

In [42]:
del p0.__dict__['x']

In [43]:
p0.x


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-43-83311df61857> in <module>()
----> 1 p0.x

AttributeError: 'Player0' object has no attribute 'x'

In [44]:
del p0.y

In [45]:
p0.y


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-45-156d4a11b74e> in <module>()
----> 1 p0.y

AttributeError: 'Player0' object has no attribute 'y'

In [46]:
p0.__dict__


Out[46]:
{'level': 1, 'name': 'Allen', 'stat': 0, 'uid': '0000'}

In [47]:
import sys

In [49]:
p1.x=2


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-49-be0c278d57cf> in <module>()
----> 1 p1.x=2

AttributeError: 'Player1' object has no attribute 'x'

In [53]:
sys.getsizeof(p0.__dict__)


Out[53]:
864

In [54]:
sys.getsizeof(p1.__slots__)


Out[54]:
96