Subclassing int for a revolving control number
Dan Sommers
me at privacy.net
Fri Jul 16 18:10:29 EDT 2004
On Fri, 16 Jul 2004 16:08:28 -0400,
Chris Cioffi <evenprimes at gmail.com> wrote:
> Hello all!
> 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...)
> Is there an "on change" kind of meta-function? (Like the onChange
> event in a GUI text control)
That all sounds like overkill, at least to my old-fashioned, minimalist
tastes. Remember, too, that Python has a "we're all adults" philosophy.
Untested:
class X12ControlNumber:
def __init__( self, initialvalue = 1 ):
self.x = initialvalue
def increment( self ):
self.x += 1
if self.x == 1000
self.x = 1
def get( self ):
return self.x
# alternately:
def __str__( self ):
return '%03d' % self.x
x = X12ControlNumber( )
print x.get( ) # prints 1
x.increment( )
print x.get( ) # prints 2
x.increment( )
:
:
:
x.increment( )
print x.get( ) # prints 998
x.increment( )
print x.get( ) # prints 999
x.increment( )
print x.get( ) # prints 1
Regards,
Dan
--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Never play leapfrog with a unicorn.
More information about the Python-list
mailing list