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)
Chris
--
Still searching for an even prime > 2! 13 1496
On Fri, 16 Jul 2004 16:08:28 -0400,
Chris Cioffi <ev********@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.
Quoth Chris Cioffi <ev********@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, do**@drizzle.com
"Chris Cioffi" <ev********@gmail.com> wrote in message
news:ma*************************************@pytho n.org... 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. <remaining snipped...>
Why does this have to subclass int? I think you are falling into the basic
object trap of confusing "is-a" and "is-implemented-using-a" that eventually
turns inheritance hierarchies into a semantic contortion. Dan Sommers'
posted class looks to do just what you need, with no extra int baggage.
-- Paul
Chris Cioffi wrote: I'm trying to subclass int such that once it reaches a certain value, it flips back to the starting count....
Others have given you the real answer -- don't bother with this.
However, it looks like fun:
class Clock(int):
def __add__(self, other):
return self.__class__(super(Clock, self
).__add__(other) % 12 or 12)
__radd__ = __add__
def __sub__(self, other):
return self + -other
def __rsub__(self, other):
return self.__class__(-self + 12) + other
def __repr__(self):
return '%s(%s)' % (type(self).__name__, int(self))
-Scott David Daniels Sc***********@Acm.Org
On Sat, 17 Jul 2004 06:16:18 GMT, Paul McGuire
<pt***@austin.rr._bogus_.com> wrote: "Chris Cioffi" <ev********@gmail.com> wrote in message news:ma*************************************@pytho n.org... 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. <remaining snipped...>
Why does this have to subclass int? I think you are falling into the basic object trap of confusing "is-a" and "is-implemented-using-a" that eventually turns inheritance hierarchies into a semantic contortion. Dan Sommers' posted class looks to do just what you need, with no extra int baggage.
Paul,
I think you've hit the answer. I shouldn't think about the control
number as an int.
The whole thing came up b/c I've been wanting to play with classes
derived from built-ins and though that this was a good fit. Once it's
put in a more realistic context my not so great rationale doesn't
quite make as much sense.
Thanks for the comments all...
Chris
--
Still searching for an even prime > 2!
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
Chris Cioffi <ev********@gmail.com> wrote in message news:<ma*************************************@pyth on.org>... 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)
If you are not interested in subtracting the counter, this is a nice
solution: from itertools import cycle for i in cycle(range(1,1000)):
.... print i
CTRL-C when you are tired ;)
Michele Simionato
Op 2004-07-16, Dan Sommers schreef <me@privacy.net>: On Fri, 16 Jul 2004 16:08:28 -0400, Chris Cioffi <ev********@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.
Sorry, but remarks like the one that follows, let me doubt that.
from http://docs.python.org/api/threads.html:
| To prevent naive misuse, you must write your own C extension to call
| this.
--
Antoon Pardon
I think the simplest solution would be just to use a generator...
************************************
def rollover(argMaxNumber=20):
while True:
for i in range(1, argMaxNumber+1):
yield i
########### test the rollover generator...
r = rollover(5)
for i in range(33):
print i, "=", r.next()
*************************************
Stephen Ferg wrote: I think the simplest solution would be just to use a generator...
************************************ def rollover(argMaxNumber=20): while True: for i in range(1, argMaxNumber+1): yield i
This can also be spelled as itertools.cycle(xrange(max_number)).
--
Ciao,
Matteo
On Tue, 20 Jul 2004, Matteo Dell'Amico wrote: Stephen Ferg wrote: I think the simplest solution would be just to use a generator...
************************************ def rollover(argMaxNumber=20): while True: for i in range(1, argMaxNumber+1): yield i
This can also be spelled as itertools.cycle(xrange(max_number)).
Watch out: itertools.cycle doesn't restart the generator when it's
exhausted; instead, it keeps a copy of all the items returned by the
iterator and loops over them.
Personally, rather than all these suggestions of python-written classes or
of itertools.cycle, I would like a C-extension module with something like
this. All it would have to be is an actually C int value with no bounds
checking. This would be usually for working with low-level data, like
bitmaps or compressed data, where you can't have longs and where you need
good performance on simple arithmetic.
On Tue, 20 Jul 2004, Calvin Spealman wrote: Personally, rather than all these suggestions of python-written classes or of itertools.cycle, I would like a C-extension module with something like this. All it would have to be is an actually C int value with no bounds checking. This would be usually for working with low-level data, like bitmaps or compressed data, where you can't have longs and where you need good performance on simple arithmetic.
numarray does this: from numarray import * array(254,UInt8)+4
2
It also greatly speeds up performance on the vector operations needed in
processing bitmaps, etc. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Mizrandir |
last post by:
I'd like to subclass numarray's array. I'd like to add some methods
and override others like __init__. I don't know how to do this and
haven't found help searching the manual or the web, can...
|
by: Emiliano Molina |
last post by:
Where can I find information on how to do this?
Specifically I am concerned about something like:
class NewList(list):
def __init__(self):
list.__init__(self)
The above code does not allow...
|
by: BJörn Lindqvist |
last post by:
A problem I have occured recently is that I want to subclass builtin
types. Especially subclassing list is very troublesome to me. But I
can't find the right syntax to use. Take for example this...
|
by: Peter Olsen |
last post by:
I want to define a class "point" as a subclass of complex.
When I create an instance
sample = point(<arglist>)
I want "sample" to "be" a complex number, but with its real and
imaginary...
|
by: Pieter Linden |
last post by:
Hi,
This question refers sort of to Rebecca Riordan's article on Access
web about subclassing entities:
http://www.mvps.org/access/tables/tbl0013.htm
How practical is this? I am writing a...
| |
by: TheStripe |
last post by:
Hello all,
Wondering if anyone has come across this problem I am having..
I am Subclassing a RadioButtonList to add some properties that I need. I am
building up
a table and adding to a...
|
by: Andrius B. |
last post by:
Hi all.
Could smb provide an Internet site or smth explaining how to use function
SetWindowSubclass in vb.net? All examples found by me are in C++ :(
Thanks.
|
by: antonyliu2002 |
last post by:
I have a Windows console application, which takes around 3 minutes to
complete the execution.
I am interested in implementing something animate while users are
waiting for the process to...
|
by: BiDi |
last post by:
I have been trying to subclass complex, but I am not able to get the
right-hand arithmetic operators working.
As shown below, if an object of my subclass 'xcomplex' is added on the
right of a...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
| |