欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python自定义一个数组类,支持数组之间的四则运算和其他常见方法

程序员文章站 2023-01-30 08:19:20
class MyArray: '''保证输入的内容是整型、浮点型''' def ___isNumber(self, num): if not isinstance(num, (int,float)): return False return True #开始写构造函数,接受可变长度的数组 def _ ......
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