添加两个复数代码:

时间:2015-05-26 08:01:20

标签: python

我遇到了以下代码,用于添加/减去两个复数。我是python的初学者,所以我无法完全理解代码。你能帮我理解下面的代码:

  1. str 方法在以下代码中的重要性。
  2. "其他"的重要性添加 sub 方法中的变量,即输入中返回的值other.a和other.b如何。

     class ComplexNumber(object):
         def __init__(self, a, b):
             '''a is real part and b is the imaginary part.'''
             self.a = a
             self.b = b
    
         def __str__(self):
             '''Represent complex number in a restrict way.'''
             if self.b == 0:
                 return "%.2f" % self.a
             elif self.a == 0:
                 #return "- %.2fi" % abs(self.b)
                 return "%.2fi" % self.b
             elif self.b < 0:
                 return "%.2f - %.2fi" % (self.a, abs(self.b))
             else:
                 return "%.2f + %.2fi" % (self.a, self.b)
    
         def __add__(self, other):
             return ComplexNumber(self.a + other.a, self.b + other.b)
    
         def __sub__(self, other):
             return ComplexNumber(self.a - other.a, self.b - other.b)
    
      a, b = [float(item) for item in raw_input().split()]
      c1 = ComplexNumber(a, b)
      a, b = [float(item) for item in raw_input().split()]
      c2 = ComplexNumber(a, b)
    
      print c1 + c2
      print c1 - c2
    

2 个答案:

答案 0 :(得分:1)

#将两个复数相加

 x=complex(input())
 y=complex(input())
 z=x+y
 print("The sum of complex numbers:",z)

 #output will be 
 3+2j
 4+5j
 The sum of complex numbers:7+7j'

答案 1 :(得分:0)

__str__()是定义如何将对象转换为字符串的方法。

other变量是您要添加到此对象的对象。 “其他”对象。