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その他の拡張
Python3 の例