Python 複數屬性及操作介紹

複數是由一個實數和一個虛數組合構成,表示爲:x+yj,一個複數是一對有序浮點數 (x,y),其中 x 是實數部分,y 是虛數部分。

Python 複數屬性及操作介紹Python 複數屬性及操作介紹

Python 語言中有關複數的概念:

  1. 虛數不能單獨存在,它們總是和一個值爲 0.0 的實數部分一起構成一個複數
  2. 複數由實數部分和虛數部分構成
  3. 表示虛數的語法:real+imagej
  4. 實數部分和虛數部分都是浮點數
  5. 虛數部分必須有後綴j或J
#coding=utf8

aa=123-12j
print aa.real  # output 實數部分 123.0  
print aa.imag  # output虛數部分 -12.0

輸出結果爲:

123.0
-12.0

複數的內建屬性:

複數對象擁有數據屬性,分別爲該複數的實部和虛部。

複數還擁有 conjugate 方法,調用它可以返回該複數的共軛複數對象。

複數屬性:real(複數的實部)、imag(複數的虛部)、conjugate()(返回複數的共軛複數)

#coding=utf8

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()

本文地址:https://www.linuxprobe.com/attributes-and-operations.html

Linux命令大全:https://www.linuxcool.com/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章