本文實例講述了Python復數屬性和方法運算操作。分享給大家供大家參考,具體如下:
#coding=utf8'''''復數是由一個實數和一個虛數組合構成,表示為:x+yj一個負數時一對有序浮點數(x,y),其中x是實數部分,y是虛數部分。Python語言中有關負數的概念:1、虛數不能單獨存在,它們總是和一個值為0.0的實數部分一起構成一個復數2、復數由實數部分和虛數部分構成3、表示虛數的語法:real+imagej4、實數部分和虛數部分都是浮點數5、虛數部分必須有后綴j或J復數的內建屬性:復數對象擁有數據屬性,分別為該復數的實部和虛部。復數還擁有conjugate方法,調用它可以返回該復數的共軛復數對象。復數屬性:real(復數的實部)、imag(復數的虛部)、conjugate()(返回復數的共軛復數)'''class Complex(object): '''''創建一個靜態屬性用來記錄類版本號''' version=1.0 '''''創建個復數類,用于操作和初始化復數''' def __init__(self,rel=15,img=15j): self.realPart=rel self.imagPart=img #創建復數 def creatComplex(self): return self.realPart+self.imagPart #獲取輸入數字部分的虛部 def getImg(self): #把虛部轉換成字符串 img=str(self.imagPart) #對字符串進行切片操作獲取數字部分 img=img[:-1] return float(img)def test(): print "run test..........." com=Complex() Cplex= com.creatComplex() if Cplex.imag==com.getImg(): print com.getImg() else: pass if Cplex.real==com.realPart: print com.realPart else: pass #原復數 print "the religion complex is :",Cplex #求取共軛復數 print "the conjugate complex is :",Cplex.conjugate()if __name__=="__main__": test()
運算結果:

希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答