Python自定義一個數組類,支持數組之間的四則運算和其他常見方法

class MyArray:
'''保證輸入的內容是整型、浮點型'''
def ___isNumber(self, num):
if not isinstance(num, (int,float)):
return False
return True

#開始寫構造函數,接受可變長度的數組
def __init__(self, *args):
if args == None:
self.__value = []
else:
for a in args:
if not self.___isNumber(a):
print('All elements must be number!')
#self.__value 是一個數組
self.__value = list(args)

#打印輸出當前的self.__value
def printSelf(self):
#這個self是一個地址
print(self)
#這個self.__value是一個數組
print(self.__value)

#重載len(Array)這個方法
def __len__(self):
return len(self.__value)

#append方法
def append(self, other):
self.__value.append(other)
#注意:此處不能夠直接return self.__value.append(other)
#這個方法執行后沒有返回值
return self.__value

#重載運算符+
def __add__(self,other):
if self.___isNumber(other):
#如果other 是一個數,則數組裡每一個元素都加上other
array = MyArray()
array.__value = [ i + other for i in self.__value]
return array.__value
elif isinstance(other,MyArray):
#如果other 是一個數組,則兩個數組對應位置的數相加
if (len(self.__value) == len(other.__value)):
array = MyArray()
array.__value = [i+j for i,j in zip(self.__value,other.__value)]
return array.__value
else:
print('The size must be equal!')
else:
print('Please input a array or a num!')


#重載運算符 / 浮點數除法,返回浮點數
def __truediv__(self,other):
if self.___isNumber(other):
if other == 0:
print("Zero cant be this number!")
return
array = MyArray()
array.__value = [i / other for i in self.__value]
return array.__value
else:
print("It is must be a number except zero!")

#重載運算符 // 整數除法,返回不大於結果的最大的一個整數
def __floordiv__(self,other):
if isinstance(other,int):
if other == 0:
print("Zero cant be this number!")
return
array = MyArray()
array.__value = [i // other for i in self.__value]
return array.__value
else:
print("Tt is must be a number except zero!")

#重載運算符% 取餘數
def __mod__(self,other):
if isinstance(other,int):
if other == 0:
print("Zero cant be this number!")
return
array = MyArray()
array.__value = [i % other for i in self.__value]
return array.__value
else:
print("Tt is must be a number!")

#根據數組index查看元素
def __getitem__(self,index):
arrayLength = len(self.__value)
if isinstance(index,int) and (0 <= index <= arrayLength):
return self.__value[index]
else:
print("Index must be a Inteager which is less than", arrayLength-1)

#查看元素是否在該列表
def __contains__(self,other):
if other in self.__value:
return True
return False

#數組比較
def __lt__(self,other):
if not isinstance(other,MyArray):
print("It is must be the type of MyArray")
return False
if self.__value < other.__value:
return True
return False



点赞

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *