'''自定义数组类,实现数组中数字之间的四则运算,内积运算,大小比较,数组元素访问修改及成员测试等功能'''
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)
05-08 15:51