python3.4中自定義數組類(即重寫數組類)


'''自定義數組類,實現數組中數字之間的四則運算,內積運算,大小比較,數組元素訪問修改及成員測試等功能'''
class MyArray: '''保證輸入值為數字元素(整型,浮點型,復數)'''
    def ___isNumber(self, n): if not isinstance(n,(int,float,complex)): return False return True #構造函數,進行必要的初始化
    def __init__(self,*args): if not args: self.__value = [] else: for arg in args: if not self.___isNumber(arg): print('All elements must be numbers') return self.__value = list(args) @property def getValue(self): return self.__value
    #析構函數,釋放內部封裝的列表
    def __del__(self): del self.__value
    #重載運算符+
    def __add__(self, other): '''數組中每個元素都與數字other相加,或者兩個數組相加,得到一個新數組'''
        if self.___isNumber(other): #數組與數字other相加
            b = MyArray() b.__value = [item + other for item in self.__value] return b elif isinstance(other,MyArray): #兩個數組對應元素相加
            if (len(other.__value) == len(self.__value)): c = MyArray() c.__value = [i+j for i,j in zip(self.__value,other.__value)] return c else: print('Lenght no equal') else: print('Not supported') #重載運算符-
    def __sub__(self, other): '''數組元素與數字other做減法,得到一個新數組'''
        pass
    #重載運算符*
    def __mul__(self, other): '''數組元素與數字other做乘法,或者兩個數組相乘,得到一個新數組'''
        pass
    #重載數組len,支持對象直接使用len()方法
    def __len__(self): return len(self.__value) #支持使用print()函數查看對象的值
    def __str__(self): return str(self.__value) if __name__ == "__main__": print('Please use me as a module.') x = MyArray(1,12,15,14,1) print('%s\n array lenghts:%d'%(x,len(x))) x = x+2
    print(x.getValue)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM