473,695 Members | 2,340 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Subclassing complex with computed arguments

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
define some new methods and over-ride some of complex's existing ones.

This is probably very simple, but it hasn't been simple to me.

Please feel free to flame me with RTFM as long as you also tell me
where in TFM to R.

If you respond, please send a copy directly to me. I seldom have
access to this group. (My primary network isn't connected to the
internet.)

Peter
pcolsen-at-comcast.net
Jul 18 '05 #1
3 1691
I need a clarification. Does "sample" have to be an instance of complex or
can it be a subclass of complex? So can it be an instance of point as long
as point is a subclass of complex?

If "sample" has to be an instance of complex and not of a subclass, I think
you need to subclass point from complex and override the __new__() method to
return an instance of complex and override __init__() to use all your
arglist. In that case you also need yet another method to actually create
instances of point.

If "sample" can be an instance of a subclass of complex, I think you can
just subclass point from complex and override only __init__().

There is more in the details I guess, but I would like to first see an
answer to the above questions.

Dan

"Peter Olsen" <pc*****@comcas t.net> wrote in message
news:a8******** *************** ***@posting.goo gle.com...
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
define some new methods and over-ride some of complex's existing ones.

This is probably very simple, but it hasn't been simple to me.

Please feel free to flame me with RTFM as long as you also tell me
where in TFM to R.

If you respond, please send a copy directly to me. I seldom have
access to this group. (My primary network isn't connected to the
internet.)

Peter
pcolsen-at-comcast.net

Jul 18 '05 #2
Peter Olsen wrote:
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
define some new methods and over-ride some of complex's existing ones.


I have come up with two solutions to this. They both have warts.

Disclaimer: I have not extensively tested either of these. In
particular, I have not tested all the numeric operations to make sure
they give correct results!

The first attempt was to subclass complex directly, overriding __new__()
to process the input parameters, and delegating all the numeric special
methods to the base class implementation. The delegation wrapper
converts the returned result back to a point.

The trick to getting this to work was to realize that, for example,
complex.__add__ (self, y) requires an actual complex instance for self.
If self is a subclass of complex it returns NotImplemented. So my
delegation wrapper constructs a new complex object before calling the
base class method.

The wart in this implementation is that mixed operations with complex
don't always return a point. If the complex is the left operand,
complex.__op__ is called directly and the result is not wrapped back to
a point.

Here is the implementation:

############## point.py ############### #
''' A subclass of complex that supports the full range of complex
numeric operations
by subclassing complex.
p=point(1,2)
p point(1+2j) p+1 point(2+2j) 1+p (2+2j) p-1 point(2j)
c=complex(1,2)
p+c point(2+4j)

A point can be used where a complex is expected - though the result
is a complex,
not a point:
import cmath
cmath.sqrt(p) (1.272019649514 069+0.786151377 75742328j)

This doesn't work correctly - it calls complex.__add__ () directly
and the result doesn't get wrapped:
c+p (2+4j)
'''

class point(complex):
def __new__(cls, *args, **kwds):
if len(args) == 2:
# return complex.__new__ (cls, args[0]*2, args[1]*2) # Special
args processing goes here
return complex.__new__ (cls, args[0], args[1])
return complex.__new__ (cls, *args, **kwds)

def __str__(self):
return self.__repr__()

def __repr__(self):
s = complex.__repr_ _(self)
if s.startswith('( '):
return 'point' + s
return 'point(%s)' %s
def makeWrapper(att r):
def wrapper(self, *args):
val = getattr(complex , attr)(complex(s elf), *args)
# print attr, args, val
return point(val)
return wrapper

for special in ['__abs__', '__add__', '__div__', '__divmod__',
'__floordiv__', '__mod__', '__mul__', '__neg__',
'__pos__', '__pow__', '__radd__', '__rdiv__',
'__rdivmod__', '__reduce__', '__reduce_ex__' ,
'__rfloordiv__' , '__rmod__', '__rmul__',
'__rpow__', '__rsub__', '__rtruediv__',
'__sub__', '__truediv__']:
setattr(point, special, makeWrapper(spe cial))
def _test():
import doctest, point
return doctest.testmod (point)

if __name__ == "__main__":
_test()

############### ############### #############

My second attempt uses delegation rather than subclassing. point
instances have a complex attribute and delegate operations to it.

The trick to getting this one to work was to realize that I had to call
coerce() explicitly in my wrapper function.

The wart in this implementation is that points are not instances of
complex, so to pass a point to e.g. cmath.sqrt(), you have to explicitly
convert to a complex.

I think this implementation is probably safer, since it fails noisily
and failures are easy to fix, whereas the first implementation could
silently give errors (depending on how point and complex actually differ).

Here is the implementation:

############### ## point2.py ############### #####

''' A class that supports a full range of complex numeric operations by
delegating
to an instance of complex.
p=point(1,2)
p point(1+2j) p+1 point(2+2j) 1+p point(2+2j) p-1 point(2j) p-4j point(1-2j)
c=complex(1,2)
p+c point(2+4j) c+p point(2+4j)

Since point does not subclass complex, it must be explicitly coerced
to a complex when one is needed:
import cmath
cmath.sqrt(p) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: a float is required
cmath.sqrt(comp lex(p))

(1.272019649514 069+0.786151377 75742328j)
'''

class point(object):
def __init__(self, *args, **kwds):
if len(args) == 1 and isinstance(args[0], complex):
self.c = args[0]
if len(args) == 2:
# self.c = complex(args[0]*2, args[1]*2) # Special args
processing goes here
self.c = complex(args[0], args[1])
else:
self.c = complex(*args, **kwds)

def __str__(self):
return self.__repr__()

def __repr__(self):
s = repr(self.c)
if s.startswith('( '):
return 'point' + s
return 'point(%s)' %s

def __complex__(sel f):
return self.c
def makeWrapper(att r):
def wrapper(self, y):
x, y = coerce(self.c, y)
val = getattr(x, attr)(y)
# print attr, x, y, val
return point(val)
return wrapper
for special in ['__abs__', '__add__', '__div__', '__divmod__',
'__floordiv__', '__mod__', '__mul__', '__neg__',
'__pos__', '__pow__', '__radd__', '__rdiv__',
'__rdivmod__', '__reduce__', '__reduce_ex__' ,
'__rfloordiv__' , '__rmod__', '__rmul__',
'__rpow__', '__rsub__', '__rtruediv__',
'__sub__', '__truediv__']:
setattr(point, special, makeWrapper(spe cial))
def _test():
import doctest, point2
return doctest.testmod (point2)

if __name__ == "__main__":
_test()

############### ############### ######

HTH,
Kent
Jul 18 '05 #3
On 25 Nov 2004 14:30:18 -0800, pc*****@comcast .net (Peter Olsen) wrote:
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
define some new methods and over-ride some of complex's existing ones.

This is probably very simple, but it hasn't been simple to me.

Please feel free to flame me with RTFM as long as you also tell me
where in TFM to R.

If you respond, please send a copy directly to me. I seldom have
access to this group. (My primary network isn't connected to the
internet.)

Well, let us know how it goes, and maybe tell the curious what your
application is ;-). BTW, as others have explained, the initialization
of values is done via complex.__new__ , not via __init__. You can override that
too, but I just let it be inherited to do its normal thing.

The following is a way to automate wrapping complex so as to return point instances
from the various operations. Not tested beyond what you see, and it won't
be a speed demon, but might be something to explore your concept with.

If you want to add special methods, you can do it like __repr__ and __coerce__
in the example, or you could add them after. Or you could use a proper metaclass
instead of doing it the function way.

Python 2.4b1 (#56, Nov 3 2004, 01:47:27)
[GCC 3.2.3 (mingw special 20030504-1)] on win32
Type "help", "copyright" , "credits" or "license" for more information.
class point(complex): ... """complex wrapper subclass point"""
... def __metaclass__(c name, cbases, cdict):
... P = type(cname, cbases, cdict)
... def mkm(name, func):
... def m(*args): return P(func(*args))
... m.__name__ = name
... return m
... for name, func in complex.__dict_ _.items():
... if callable(func) and name not in ['__coerce__',
... '__doc__', '__float__', '__getattribute __', '__getnewargs__ ',
... '__hash__', '__int__', '__long__', '__new__', '__repr__',
... '__str__', 'imag', 'real']:
... setattr(P, name, mkm(name, func))
... def __coerce__(self , other): return self, P(other)
... P.__coerce__ = __coerce__
... def __repr__(self): return '<point %s>'% complex.__repr_ _(self)
... P.__repr__ = __repr__
... return P
... p = point(3, 4)
p <point (3+4j)> p+1 <point (4+4j)> p-1 <point (2+4j)> 1-p <point (-2-4j)> 1+p <point (4+4j)> p*p <point (-7+24j)> p*p.conjugate() <point (25+0j)> abs(p) <point (5+0j)> print p, type(p), repr(p) (3+4j) <class '__main__.point '> <point (3+4j)> p.imag 4.0 p.real

3.0

You can explore further, and fix the bugs ;-)
I don't know what __getnewargs__ does, so I left it alone to be inherited.

Regards,
Bengt Richter
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
8899
by: Fuzzyman | last post by:
I recently went through a bit of a headache trying to subclass string.... This is because the string is immutable and uses the mysterious __new__ method rather than __init__ to 'create' a string. To those who are new to subclassign the built in types, my experiences might prove helpful. Hopefully not too many innacuracies :-) I've just spent ages trying to subclass string.... and I'm very proud to say I finally managed it ! The...
3
1600
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.
2
5155
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 = ....
3
1935
by: Mark E. Fenner | last post by:
Hello all, I was migrating some code from sets.ImmutableSet to frozenset and noticed the following: ******code******** #!/usr/bin/env python from sets import ImmutableSet
11
3831
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you experts. I would like to produce Javascript classes that can be "subclassed" with certain behaviors defined at subclass time. There are plenty of ways to do this through prototyping and other techniques, but these behaviors need to be static and...
4
11028
by: Erik Johnson | last post by:
I ran into a problem I didn't understand at first. I got part of it figured out. Let me first demonstrate the original problem: class Super(object): def __init__(self): self._class = 'Super' def hello(self): print "%s says 'Hello'" % self._class
1
1407
by: Christian Heimes | last post by:
Rick King schrieb: datetime.date is a C extension class. Subclassing of extension classes may not always work as you'd expect it. Christian
9
9942
by: void main | last post by:
I'm rather new to complex numbers in C and was wondering, how do I initialize a complex variable properly if the imaginary part is 0. I tried -------- #include <complex.h> float complex c = 1.0f; --------
4
1449
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)
0
8649
marktang
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...
0
9137
Oralloy
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...
1
8864
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,...
0
8838
tracyyun
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...
1
6506
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5842
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
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...
0
4592
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
1986
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.