gpt4 book ai didi

python - 从复杂对象覆盖 __init__

转载 作者:太空狗 更新时间:2023-10-30 02:58:22 26 4
gpt4 key购买 nike

我想要一个自定义的 complex 类,它可以获取一个字符串作为输入 ("1 2") 并读取 realimag 部分。

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__ 中分配了realimag 的值。 .

__new____init__ 之前运行,负责对象的创建。执行(考虑 myComplexcomplex)是这样的:

  1. myComplex("1 1")

  2. myComplex.__new__(cls, inp)

  3. complex.__new__(cls, real, imag)

  4. 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com