Python Forum

Full Version: I have subclassed complex, but don't understand why it's working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm using python 3.5. I want a class that's essentially a complex number, and behaves as such in arithmetic, but for reasons that I won't go into, I would like it to carry around other things for convenience.

So without thinking too hard, I subclassed complex, accidentally omitting the call to super(), and I find it works. This is a rather stripped-down version of the class.

class Point(complex):
    def __init__(self, z_init):
        # super().__init__()
        self.id = 'spam'

    def __str__(self):
        return 'point {} ({}+{}j)'.format(self.id, self.real, self.imag)                                        

p = Point(3+2j)
print(p)
Output:
point spam (3.0+2.0j)
The thing is, I don't understand how it works. There appears to be no connection between the z_init parameter, and the .real and .imag attributes. It hasn't thrown an error at me. When I include super(), it still works exactly the same way. However, even with that call, super() takes no parameters, so there's still no explicit route from z_init to the object.

I presume that inheriting from complex perhaps does magic things, making assumptions about the parameters to the __init__ function? I've looked through the docs for information on this, but they are not what one would call noob-friendly. I'm a bit nervous about relying on this behaviour when I don't understand it. But it's working for me at the moment.

I would imagine my guess is something like correct, as it would not work otherwise. Is it documented anywhere whether this should work, or how it works? Is it dangerous, perhaps likely to change in later versions?
(Feb-07-2018, 04:27 PM)NeilUK Wrote: [ -> ]The thing is, I don't understand how it works.
Before the instance's __init__() method, the classmethod __new__() is called to create the instance. In your case, complex.__new__(Point, z_init) was called and returned the instance self.