class Complex(object):
def __init__(self, real, imaginary):
self.real=real
self.imaginary=imaginary
def __add__(self, no):
self.real=self.real+no.real
self.imaginary=self.imaginary+no.imaginary
def __str__(self):
if self.imaginary == 0:
result = "%.2f+0.00i" % (self.real)
else:
result = "%.2f+%.2fi" % (self.real, self.imaginary)
我想以 str 方法中定义的格式在添加函数内打印两个复数的和,而不需要操作 str 函数。 这意味着如何从添加方法访问 str 方法中定义的结果变量。
答案 0 :(得分:0)
如果我正确理解您的问题,您希望在添加中打印 str 方法的结果。所以我认为这是最好的决定:
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, no):
self.real = self.real + no.real
self.imaginary = self.imaginary + no.imaginary
print(str(self))
def __str__(self):
if self.imaginary == 0:
result = "%.2f+0.00i" % (self.real)
else:
result = "%.2f+%.2fi" % (self.real, self.imaginary)
return result
a = Complex(1, 2)
b = Complex(3, 4)
a + b