1. 程式人生 > >Python複數屬性和方法操作例項

Python複數屬性和方法操作例項

#coding=utf8
'''
複數是由一個實數和一個虛數組合構成,表示為:x+yj
一個負數時一對有序浮點數(x,y),其中x是實數部分,y是虛數部分。
Python語言中有關負數的概念:
1、虛數不能單獨存在,它們總是和一個值為0.0的實數部分一起構成一個複數
2、複數由實數部分和虛數部分構成
3、表示虛數的語法:real+imagej
4、實數部分和虛數部分都是浮點數
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()