导读 在编程的世界里,复数是一个非常基础且重要的概念。今天,让我们一起动手实现一个属于自己的复数类——`Complex`!🎉首先,我们需要定义这...
在编程的世界里,复数是一个非常基础且重要的概念。今天,让我们一起动手实现一个属于自己的复数类——`Complex`!🎉
首先,我们需要定义这个类的基本结构。一个复数由实部和虚部组成,所以我们可以用两个属性来表示它。接着,我们要让这个类能够像普通的数字一样进行加法操作。通过重载运算符 `+`,我们可以轻松地完成两复数相加的操作。😎
```python
class Complex:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __add__(self, other):
new_real = self.real + other.real
new_imag = self.imag + other.imag
return Complex(new_real, new_imag)
def __str__(self):
return f"{self.real} + {self.imag}i"
```
有了这个类后,你可以像这样使用它:
`c1 = Complex(3, 4)`
`c2 = Complex(1, 2)`
`result = c1 + c2`
`print(result)` → 输出:`4 + 6i`
是不是很酷?💪 这样一来,你就掌握了如何用面向对象的方式处理复数问题啦!快来试试吧!💫