有没有可能创建一个继承自复杂类但基于额外参数计算值的Python类?

9w11ddsr  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(81)

我试图创建一个自定义类,从一个复杂的类继承,但我无法实现我想要的。下面是一个代码示例:

class MyComplex(complex):
    def __init__(self, real, imag, imag2):
        super().__init__(real, imag + imag2)

# Create an instance of MyComplex with custom initialization parameters
my_complex = MyComplex(3.0, 4.0, 5.0)

# You can now use my_complex just like a regular complex number
print(my_complex)  # Output: (3+4j)
print(my_complex.real)  # Output: 3.0
print(my_complex.imag)  # Output: 4.0

但它返回一个TypeError: complex() takes at most 2 arguments (3 given)
如果我尝试使用__new__()函数,那么我可以创建继承的类,但不可能使用更多的参数来初始化值,也不可能在__init__()函数中更新它们,因为它返回AttributeError: readonly attribute
有没有办法实现我的目标?

oxf4rvwz

oxf4rvwz1#

是的,但是记住complex是一个不可变的对象,所以你不能像继承可变(用户定义的)类那样继承。相反,这是通过dunderscore运算符new实现的:

class MyComplex(complex):                                                                               
    def __new__(self, real, imag, imag2):                                                               
        return super(MyComplex, self).__new__(self, real, imag+imag2)

注意,这样定义的第一个print语句返回(3+9j)
newinithttps://builtin.com/data-science/new-python
您还应该注意,您需要重载运算符,以便它们返回正确的类型。例如

print(MyComplex(1.0, 2.0, 3.0) + MyComplex(2.0, 3.0, 4.0))

将打印(3+12j),一个complex类型的对象,而不是MyComplex,正如你一开始所希望的那样。

相关问题