Subclassing int for a revolving control number

Donn Cave donn at drizzle.com
Sat Jul 17 00:54:05 EDT 2004


Quoth Chris Cioffi <evenprimes at gmail.com>:

| 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...)

Do bear in mind that ints don't change value.  All you need is
1) control the initial value of the object (in __init__) and
2) make __add__ return your type instead of int. 

class OI:
	max = 16
	def __init__(self, t):
		if t > self.max:
			t = t - self.max
		self.value = t
	def __add__(self, k):
		return OI(self.value + k)
	def __str__(self):
		return str(self.value)
	def __repr__(self):
		return 'OI(%s)' % self.value
	def __cmp__(self, v):
		return cmp(self.value, v)

You could implement a mutable counter, but for most applications
the way int works is less confusing - like, what should this do?
  i = OI(1)
  j = i
  i += 1
  print i, j

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list