I'm doing an optimisation on the complex plane, with an expensive function.
I'd like to have a class that's a complex number, which behaves like a complex number for arithmetic, but also has the result of the function, and a few convenient debug assists tacked onto it.
I threw the following together, and it was only later that I realised I didn't understand why it should be working, as I'd initially omitted the call to super().__init__()
. I don't understand how the z argument is setting the .real and .imag parts of the number, or that it's not throwing an error at me. When I added the super(), it still worked exactly the same. However, super doesn't take an argument, so I don't see how that would magic the parameter z into .real and .imag either.
def spam(z):
return abs(pow(z,3))
class Point(complex):
def __init__(self, z):
# super().__init__() # doesn't seem to make any difference
# super().__init__(z) # throws an error
try:
Point.serial += 1
except AttributeError:
Point.serial = 0
self.id = Point.serial
self.y = spam(z)
self.ge3 = self.y>=3
def __str__(self):
return 'point {} ({}+{}j) = {} {}'.format(self.id,
self.real,
self.imag,
self.y,
('below', 'above')[self.ge3])
p = Point(3)
q = Point(2j)
r = Point((p+q)/2)
print(p)
print(q)
print(r)
gives
point 0 (3.0+0.0j) = 27 above
point 1 (0.0+2.0j) = 8.0 above
point 2 (1.5+1.0j) = 5.859020822628983 above
Is this legal or expected behaviour? How is it working? Should I do it differently? Is it likely to stop working with future versions (3.5.2 presently)?