Sorry to be at the party for 8.5 years. You can get immutable (i.e. int). You cannot define __init__ because immutable is already created and cannot be changed (by definition). Here __new__ in handy.
class IntContainer(int): def __new__ (cls, val): ival = int.__new__(cls, val) ival._rval = 'IntContainer(%d)' % ival return ival def __repr__ (self): return self._rval In [1]: i = IntContainer(3) In [2]: i Out[2]: IntContainer(3) In [3]: repr(i) Out[3]: 'IntContainer(3)' In [4]: str(i) Out[4]: '3' In [5]: i + 5 Out[5]: 8 In [6]: 4 + i Out[6]: 7 In [7]: int(i) Out[7]: 3 In [8]: float(i) Out[8]: 3.0
Now to answer your question about conversion operators. You can also define __int__ , __long__ , __float__ and obviously __str__ . To convert or translate an arbitrary object, you will most likely need to change another object to get what you want. You can use the __new__ method of this other object. Or, if another object has already been created, try using __call__ .
ayce
source share