定义一个复数类,包括实部和虚部成员变量、构造方法、输出复数、以及两个复数的加法__add__( )、乘法__mul__( )和大于__gt__( )运算定义
时间: 2023-06-03 11:02:19 浏览: 130
c.rar_class Complex_show_编写一个C ++类
5星 · 资源好评率100%
好的,以下是可以回答的代码:
class Complex:
def __init__(self, realpart, imagpart):
self.realpart = realpart
self.imagpart = imagpart
def __str__(self):
return '{} + {}i'.format(self.realpart, self.imagpart)
def __add__(self, other):
return Complex(self.realpart + other.realpart, self.imagpart + other.imagpart)
def __mul__(self, other):
return Complex(self.realpart*other.realpart - self.imagpart*other.imagpart,
self.realpart*other.imagpart + self.imagpart*other.realpart)
def __gt__(self, other):
if self.realpart > other.realpart and self.imagpart > other.imagpart:
return True
else:
return False
# 调用
c1 = Complex(3, 4)
c2 = Complex(2, 3)
print(c1 + c2)
print(c1 * c2)
print(c1 > c2)
阅读全文