Pre-increment integer subclass in Python
May 31, 2011
At work today I claimed ++a could be used to increment a Python variable by subclassing types.IntType.
My coworker challenged me to implement such a subclass, the result is shown below.
from types import IntType
class IncType(IntType):
inc = 0
value = 0
def __new__(cls, val, *args, **kwargs):
print "I got new'd"
inst = super(IncType, cls).__new__(cls, val)
inst.value = val
return inst
def __pos__(self, *args, **kwargs):
self.inc += 1
print "I got unary plus'd",self.inc,'times'
if self.inc >= 2:
self.value += 1
self.inc -= 2
inst = super(IncType, self).__new__(IncType,self.value.__pos__())
inst.inc = self.inc
inst.value = self.value
return inst
# def __neg__(self, *args, **kwargs):
# print "I got unary neg'd"
# return self
Thus an interactive Python session gives:
>>> ++IncType(1)
I got new'd
I got unary plus'd 1 times
I got unary plus'd 2 times
2
>>>