Overwrite __init__ from a complex object

I want to have a custom class complexthat can receive a string as input ( "1 2") and read there realand imag.

class myComplex(complex):
    def __init__(self, inp):
        real, imag = inp.split()
        self.real = float(real)
        self.imag = float(imag)


comp = myComplex("1 2")
print comp # (1+2j)

but I get the error:

Traceback (most recent call last):
  File "my_complex.py", line 8, in <module>
    comp1 = myComplex(inp1)
ValueError: complex() arg is a malformed string

Does this mean that mine is __init__not overwriting one of the ones complex, or have I missed something fundamental?

+4
source share
1 answer

Python complexassigns values ​​to realand imagin __new__.

__new__runs before __init__and is responsible for creating the object. The implementation (taking into account myComplexand complex) is as follows:

  • myComplex("1 1")

  • myComplex.__new__(cls, inp)

  • complex.__new__(cls, real, imag)

  • myComplex.__init__(self, inp)

(No complex.__init__, since it myComplex.__init__does not cause it)

, "1 2" __init__.

__new__:

class myComplex(complex):
    def __new__(cls, inp):
        real, imag = inp.split()
        return super(myComplex, cls).__new__(cls, float(real), float(imag))
+4

Source: https://habr.com/ru/post/1619657/


All Articles