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
原文地址:https://www.cnblogs.com/motorye/p/10891035.html
时间: 2024-11-08 22:59:51