module.py中的:
import math
class Complex:
def __init__(self,real=0,imag=0):
self.real=real
self.imag=imag
def add(self,other):
if isinstance(other,Complex):
self.real=self.real+other.real
self.imag=self.imag+other.imag
def output(other):
if isinstance(other, Complex):
if(other.imag>=0):
print(other.real,"+",other.imag,"i")
else:
print(other.real,"-",(-1)*other.imag,"i")
def abs(other):
if isinstance(other, Complex):
return math.sqrt(other.real*other.real+other.imag*other.imag)
def is_equal(a1,a2):
if isinstance(a1,Complex) and isinstance(a2,Complex):
if(a1.real==a2.real and a1.imag==a2.imag):
return "true"
else:
return "false"
def is_not_equal(a1,a2):
if isinstance(a1,Complex) and isinstance(a2,Complex):
if(a1.real==a2.real and a1.imag==a2.imag):
return "false"
else:
return "true"
def add(a1,a2):
if isinstance(a1, Complex) and isinstance(a2, Complex):
return Complex(a1.real+a2.real,a1.imag+a2.imag)
2024_10_21.py中的:
import module
import copy
def test():
print("類測試成員:")
c1=module.Complex()
c2=module.Complex(3,-4)
c3=module.Complex(3.5)
c4=copy.deepcopy(c3)
print("c1=",end="")
module.output(c1)
print("c2=",end="")
module.output(c2)
print("c3=", end="")
module.output(c3)
print("c4=", end="")
module.output(c4)
print("c4.real=",c4.real,",","c4.imag=",c4.imag)
print()
print("複數運算測試:")
print("abs(c2)=",end="")
print("{:g}".format(module.abs(c2)))
c1.add(c2)
print("c1+=c2,c1=",end="")
module.output(c1)
print("c1==c2:",end="")
print(module.is_equal(c1,c2))
print("c1!=c3:",end="")
print(module.is_not_equal(c1,c3))
c4=module.add(c1,c3)
print("c4=c2+c3,c4=",end="")
module.output(c4)
test()
執行截圖: