Python 实现一个类,表示复数,并提供加法、减法等操作
我们将创建一个名为 ComplexNumber
的类,用于表示复数。复数由实部和虚部组成,我们将实现加法和减法操作。
实例
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)
def __str__(self):
return f"{self.real} + {self.imaginary}i"
# 示例使用
c1 = ComplexNumber(3, 4)
c2 = ComplexNumber(1, 2)
print("c1 + c2 =", c1 + c2)
print("c1 - c2 =", c1 - c2)
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)
def __str__(self):
return f"{self.real} + {self.imaginary}i"
# 示例使用
c1 = ComplexNumber(3, 4)
c2 = ComplexNumber(1, 2)
print("c1 + c2 =", c1 + c2)
print("c1 - c2 =", c1 - c2)
代码解析:
__init__
方法用于初始化复数的实部和虚部。__add__
方法实现了复数的加法操作,返回一个新的ComplexNumber
对象。__sub__
方法实现了复数的减法操作,返回一个新的ComplexNumber
对象。__str__
方法用于将复数对象转换为字符串形式,方便打印输出。
输出结果:
c1 + c2 = 4 + 6i c1 - c2 = 2 + 2i
点我分享笔记