我正在try 创建一个从复杂类继承的自定义类,但我无法实现我想要的.下面是一个代码示例:
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)
如果我try 使用__new__()
函数,那么我可以创建继承的类,但不可能使用更多参数来初始化值,也不可能在__init__()
函数中更新它们,因为它返回AttributeError: readonly attribute
有没有办法实现我的目标?