Python自定义一个数组类,并实现数组之间、数组与整数之间的四则运算以及内积、大小比较、成员测试和元素访问等运算。代码如下:
class MyArray:
__value=[]
__size=0
def __IsNumber(self,n):
if (not isinstance(n,int)) and (not isinstance(n,float)) and (not isinstance(n,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)
def __add__(self,n): #数组中每个元素都与数字n相加,或两个数组相加
if self.__IsNumber(n):
b=MyArray()
for v in self.__value:
b.__value.append(v+n)
return b
elif isinstance(n,MyArray):
if len(n.__value)==len(self.__value):
c=MyArray()
for i,j in zip(self.__value,n.__value):
c.__value.append(i+j)
return c
else:
print('Lenght not equal')
else:
print('Not supported')
def __sub__(self,n): #数组中每个元素都与数字n相减,或两个数组相减
if self.__IsNumber(n):
b=MyArray()
for v in self.__value:
b.__value.append(v-n)
return b
elif isinstance(n,MyArray):
if len(n.__value)==len(self.__value):
c=MyArray()
for i,j in zip(self.__value,n.__value):
c.__value.append(i-j)
return c
else:
print('Lenght not equal')
else:
print('Not supported')
def __mul__(self,n): #数组中每个元素都与数字n相乘,或两个数组相乘
if self.__IsNumber(n):
b=MyArray()
for v in self.__value:
b.__value.append(v*n)
return b
elif isinstance(n,MyArray):
if len(n.__value)==len(self.__value):
c=MyArray()
for i,j in zip(self.__value,n.__value):
c.__value.append(i*j)
return c
else:
print('Lenght not equal')
else:
print('Not supported')
def __floordiv__(self, n): #数组中每个元素都与数字n相除,或两个数组相除
if self.__IsNumber(n):
b=MyArray()
for v in self.__value:
b.__value.append(v//n)
return b
elif isinstance(n,MyArray):
if len(n.__value)==len(self.__value):
c=MyArray()
for i,j in zip(self.__value,n.__value):
c.__value.append(i//j)
return c
else:
print('Lenght not equal')
else:
print('Not supported')
def __len__(self):
return len(self.__value)
def __reper__(self):
return repr(self.__value)
def __str__(self):
return str(self.__value)
def __getitem__(self, index): #获取指定位置的元素值
if self.__IsNumber(index)and 0<=index<len(self.__value):
return self.__value[index]
else:
print('Index out of range.')
def __contains__(self, v): #成员测试运算符in
if v in self.__value:
return True
return False
def dot(self,v): #模拟向量内积
if not isinstance(v,MyArray):
print(v,'must be an instance of MyArray.')
return
if len(v) !=len(self.__value):
print('The size must be equal.')
return
b=MyArray()
for m,n in zip (v.__value,self.__value):
b.__value.append(m*n)
return sum(b.__value)
if __name__=='__main__':
print('Please use me as a moudle.')