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 1516
On Fri, 16 Jul 2004 16:08:28 -0400,
Chris Cioffi <ev********@gma il.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 X12ControlNumbe r:
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 = X12ControlNumbe r( )
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.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn.
Quoth Chris Cioffi <ev********@gma il.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.co m
"Chris Cioffi" <ev********@gma il.com> wrote in message
news:ma******** *************** **************@ python.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).__n ame__, int(self))
-Scott David Daniels Sc***********@A cm.Org
On Sat, 17 Jul 2004 06:16:18 GMT, Paul McGuire
<pt***@austin.r r._bogus_.com> wrote: "Chris Cioffi" <ev********@gma il.com> wrote in message news:ma******** *************** **************@ python.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__(sel f, other))
def __sub__(self, other):
return self.__class__( int.__sub__(sel f, other))
def makeNoimp(name) :
""" generate a method that raises a NotImplemented exception """
def noimp(self, *args):
raise NotImplementedE rror("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 NotImplementedE rror, e:
print e
Chris Cioffi <ev********@gma il.com> wrote in message news:<ma******* *************** *************** @python.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,1 000)):
.... 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********@gma il.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(argMax Number=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()
*************** *************** ******* 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 someone help?
For example imagine I just want to do something as simple as making a
subclass "NewClass" with the __init__ method overridden so that the
behaviour would be:
>>> a = NewClass(2)
>>> print a
|
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 the passing of a sequence to populate the
NewList.
|
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 class which
is supposed to be a representation of a genome:
class Genome(list):
def __init__(self):
list.__init__(self)
self =
....
|
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 parts computed in point()'s __init__ function with their
values based on the arglist. I want to compute with point instances
as though they were native complex numbers, but I want to be able to
|
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 database to track Computer
equipment/inventory as well as other devices. Computers, of course,
have software installed, so I want to keep track of that. I was
| |
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 placeHolder control. I also register an event
handler
just before finally adding MyRadioButtonList to a TableCell control.
|
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 complete.
If you have experience with Linux/Unix, you should be very familiar
with the revolving slash ( / ) or the growing dots ( ...... ), which
you normally see, when a process is taking some time.
|
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 'comlex' object, the type returned is 'complex', not
'xcomplex'.
I've tried subclassing float and it works fine (don't even need to
define __coerce__ in that case)
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |