我想要一个自定义的 complex
类,它可以获取一个字符串作为输入 ("1 2"
) 并读取 real
和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)
但是我得到了错误:
Traceback (most recent call last):
File "my_complex.py", line 8, in <module>
comp1 = myComplex(inp1)
ValueError: complex() arg is a malformed string
这是否意味着我的 __init__
没有覆盖 complex
中的那个,还是我遗漏了一些基本的东西?
最佳答案
Python 的complex
在__new__
中分配了real
和imag
的值。 .
__new__
在 __init__
之前运行,负责对象的创建。执行(考虑 myComplex
和 complex
)是这样的:
myComplex("1 1")
myComplex.__new__(cls, inp)
complex.__new__(cls, real, imag)
myComplex.__init__(self, inp)
(没有 complex.__init__
因为 myComplex.__init__
没有调用它)
这意味着参数 "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))
关于python - 从复杂对象覆盖 __init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245353/