Subclassing int for a revolving control number
Peter Otten
__peter__ at web.de
Sun Jul 18 03:32:54 EDT 2004
Chris Cioffi wrote:
> I'm trying to subclass int such that once it reaches a certain value,
> it flips back to the starting count. This is for use as an X12
> control number. Subclassing int and getting the display like I want
> it was trivial, however what's the best way to make it such that:
> 990 + 1 = 991
> 991 + 1 = 992
> ...
> 998 + 1 = 999
> 999 + 1 = 001
>
> Should I set any of the special functions like __sub__ to raise
> NotImpemented and just make my own custom assignment and __add__
> functions? (The other fucntions would make no sense in this
> context...)
OK, here's my take at the problem.
Peter
class IntN(int):
""" Base class for int % N """
def __new__(cls, value):
value = value % cls.N
if value < 0:
value = cls.N - value
return int.__new__(cls, value)
def __add__(self, other):
return self.__class__(int.__add__(self, other))
def __sub__(self, other):
return self.__class__(int.__sub__(self, other))
def makeNoimp(name):
""" generate a method that raises a NotImplemented exception """
def noimp(self, *args):
raise NotImplementedError("method %s() not implemented" % name)
return noimp
# shade the methods inherited from int
for name in "__mul__ __div__".split():
setattr(IntN, name, makeNoimp(name))
class IntK(IntN):
""" A weird way of implementing your (weird) specification """
N = 999
def __str__(self):
return str(1 + self)
__repr__ = __str__
if __name__ == "__main__":
first = IntK(995)
for i in range(10):
print first,
first += 1
print
first = IntK(5)
for i in range(10):
print first,
first -= 1
print
try:
first * 3
except NotImplementedError, e:
print e
More information about the Python-list
mailing list