在面向对象编程(OOP)的世界里,复数是一个很好的例子,可以展示如何通过定义类来模拟现实世界中的概念。复数由实部和虚部组成,可以用来表示在二维平面上的点。通过定义一个复数类,我们可以轻松地创建复数对象、执行加法、减法、乘法和除法等操作。下面,我们就从零开始,一步步了解如何定义和使用复数。
定义复数类
首先,我们需要定义一个复数类。在Python中,我们可以这样写:
class ComplexNumber:
def __init__(self, real=0.0, imag=0.0):
self.real = real
self.imag = imag
def __str__(self):
return f"{self.real} + {self.imag}i"
这里,我们定义了一个名为ComplexNumber的类,它有两个属性:real和imag,分别代表实部和虚部。我们还定义了一个__str__方法,用于将复数对象转换为字符串形式。
创建复数对象
接下来,我们可以创建复数对象。例如:
c1 = ComplexNumber(3, 4)
c2 = ComplexNumber(1, -2)
这里,我们创建了两个复数对象c1和c2,分别代表3 + 4i和1 - 2i。
执行复数运算
现在,我们已经有了复数对象,可以执行各种运算了。下面是一些常见的复数运算:
加法
class ComplexNumber:
# ... (之前的代码)
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imag + other.imag)
# 使用加法
c3 = c1 + c2
print(c3) # 输出:4 + 2i
在这个例子中,我们重写了__add__方法,用于实现复数的加法。__add__方法接收另一个复数对象作为参数,并返回一个新的复数对象,其实部和虚部分别是两个复数对象的实部和虚部之和。
减法
class ComplexNumber:
# ... (之前的代码)
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imag - other.imag)
# 使用减法
c4 = c1 - c2
print(c4) # 输出:2 + 6i
与加法类似,我们重写了__sub__方法,用于实现复数的减法。
乘法
class ComplexNumber:
# ... (之前的代码)
def __mul__(self, other):
real = self.real * other.real - self.imag * other.imag
imag = self.real * other.imag + self.imag * other.real
return ComplexNumber(real, imag)
# 使用乘法
c5 = c1 * c2
print(c5) # 输出:-5 + 10i
乘法运算稍微复杂一些,我们需要使用德莫弗公式(De Moivre’s formula)来计算结果。
除法
class ComplexNumber:
# ... (之前的代码)
def __truediv__(self, other):
denominator = other.real**2 + other.imag**2
real = (self.real * other.real + self.imag * other.imag) / denominator
imag = (self.imag * other.real - self.real * other.imag) / denominator
return ComplexNumber(real, imag)
# 使用除法
c6 = c1 / c2
print(c6) # 输出:0.6 + 0.8i
除法运算同样需要使用德莫弗公式。
总结
通过定义和使用复数类,我们可以轻松地创建复数对象并执行各种运算。这个过程展示了面向对象编程的魅力,即通过封装和抽象,将现实世界中的概念转化为计算机程序。希望这篇文章能帮助你从零开始,轻松掌握面向对象编程。
