class MyArray:
'''All the elements in this array must be numbers''' def __IsNumber(self,n):
if not isinstance(n,(int,float,compile)):
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 __del__(self):
del self.__value #重载运算符 +
#数组中每个元素都与数字other相加,或两个数组相加,返回新数组
def __add__(self, other):
if self.__IsNumber(other):
#数组中所有元素都与数字n相加
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('Length not equal')
else:
print('Not supported') #重载运算符 —
def __sub__(self, other):
if not self.__IsNumber(other):
print('- operating with',type(other),'and number type is not supported.')
return
b = MyArray()
b.__value = [item-other for item in self.__value]
return b #重载运算符 *
#数组中每个元素都与数字other相乘,返回新数组
def __mul__(self, other):
if not self.__IsNumber(other):
print('* operating with',type(other),'and number type is not supported.')
return
b = MyArray()
b.__value = [item*other for item in self.__value]
return b #重载运算符 /
#数组中每个元素都与数字other相除,返回新数组
def __truediv__(self, other):
if not self.__IsNumber(other):
print(r'/ operating with',type(other),'and number type is not supported.')
return
b = MyArray()
b.__value = [item/other for item in self.__value]
return b #重载运算符 //
#数组中每个元素都与数字other整除,返回新数组
def __floordiv__(self, other):
if not isinstance(other,int):
print(other,'is not an integer')
return
b = MyArray()
b.__value = [item//other for item in self.__value]
return b #重载运算符 %
#数组中每个元素都与数字other求余数,返回新数组
def __mod__(self, other):
if not self.__IsNumber(other):
print(r'% operating with',type(other),'and number type is not supported.')
return 0
b = MyArray()
b.__value = [item%other for item in self.__value]
return b #重载运算 **
#数组中每个元素都与数字n进行幂计算,返回新数组
def __pow__(self, power, modulo=None):
if not self.__IsNumber(power):
print('** operating with',type(power),'and number type is not supported.')
return
b = MyArray()
b.__value = [item**power for item in self.__value]
return b #重载长度计算
def __len__(self):
return len(self.__value) #直接使用该类对象作为表达式来查看对象的值
def __repr__(self):
return repr(self.__value) #支持使用print()函数查看对象的值
def __str__(self):
return str(self.__value) #追加元素
def append(self,other):
if not self.__IsNumber(other):
print('Only number can be appended.')
return
self.__value.append(other) #获取指定下标的元素值,支持使用列表或元组指定多个下标
def __getitem__(self, index):
length = len(self.__value)
#如果指定单个整数作为下标,则直接返回元素值
if isinstance(index,int) and 0<=index<length:
return self.__value[index]
elif isinstance(index,(list,tuple)):
for i in index:
if not (isinstance(i,int) and 0<=i<length):
return 'index error'
result = []
for item in index:
result.append(self.__value[item])
return result
else:
return 'index error' #修改元素值,支持使用列表或元组指定多个下标,同时修改多个元素值
def __setitem__(self, index, value):
length = len(self.__value)
#如果下标合法,则直接修改元素值
if isinstance(index,int) and 0<=index<length:
self.__value[index] = value
#支持使用列表或元组指定多个下标
elif isinstance(index,(list,tuple)):
for i in index:
if not(isinstance(i,int)) and 0<=index<length:
raise Exception('index error')
#如果下标和给的值都是列表或元组,并且个数一样,则分别为多个下表的元素修改值
if isinstance(value,(list,tuple)):
if len(index) == len(value):
for i,v in enumerate(index):
self.__value[v] = value[i]
else:
raise Exception('values and index must be of the same length')
#如果指定多个下标和一个普通值,则把多个元素修改为相同的值
elif isinstance(value,(int,float,complex)):
for i in index:
self.__value[i] = value
else:
raise Exception('value error')
else:
raise Exception('index error') #支持成员测试运算符in,测试数组中是否包含某个元素
def __contains__(self, item):
if item 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
return sum([i*j for i,j in zip(self.__value,v.__value)]) #重载运算符号==,测试两个数组是否相等
def __eq__(self, other):
if not isinstance(other,MyArray):
print(other+'must be an instance of MyArray.')
return False
if self.__value == v.__value:
return True
return False #重载运算<,比较两个数组大小
def __lt__(self, other):
if not isinstance(other,MyArray):
print(other,'must be an instance of MyArray.')
return False
if self.__value < other.__value:
return True
return False
if __name__ == '__main__':
print('Please use me as a module')
array = MyArray(1,2,4,6,7)
a=array.__mul__(2)
print(a)
#######输出######

Please use me as a module
[2, 4, 8, 12, 14]

python_重写数组的更多相关文章

  1. Vue2.0响应式原理以及重写数组方法

    // 重写数组方法 let oldArrayPrototype = Array.prototype; let proto = Object.create(oldArrayPrototype); ['p ...

  2. python3.4中自定义数组类(即重写数组类)

    '''自定义数组类,实现数组中数字之间的四则运算,内积运算,大小比较,数组元素访问修改及成员测试等功能''' class MyArray: '''保证输入值为数字元素(整型,浮点型,复数)''' de ...

  3. Python_重写集合

    class Set(object): def __init__(self,data=None): if data == None: self.__data = [] else: if not hasa ...

  4. ES6数组扩展

    前面的话 数组是一种基础的JS对象,随着时间推进,JS中的其他部分一直在演进,而直到ES5标准才为数组对象引入一些新方法来简化使用.ES6标准继续改进数组,添加了很多新功能.本文将详细介绍ES6数组扩 ...

  5. 数组中的each 和 jquery 中的 each

    数组的实例上都有一个叫做 forEach 的方法,这个方法定义在 Array.prototype 上,所以数组的所有实例都可以使用 forEach 这个方法. forEach 方法的语法结构如下: v ...

  6. ES里关于数组的拓展

    一.静态方法 在ES6以前,创建数组的方式主要有两种,一种是调用Array构造函数,另一种是用数组字面量语法,这两种方法均需列举数组中的元素,功能非常受限.如果想将一个类数组对象(具有数值型索引和le ...

  7. 迷你MVVM框架 avalonjs1.5 入门教程

    avalon经过几年以后,已成为国内一个举足轻重的框架.它提供了多种不同的版本,满足不同人群的需要.比如avalon.js支持IE6等老旧浏览器,让许多靠政府项目或对兼容性要求够高的公司也能享受MVV ...

  8. 230行实现一个简单的MVVM

    作者:mirone链接:https://zhuanlan.zhihu.com/p/24451202来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. MVVM这两年在前端届 ...

  9. 谈谈数据监听observable的实现

    一.概述 数据监听实现上就是当数据变化时会通知我们的监听器去更新所有的订阅处理,如: var vm = new Observer({a:{b:{x:1,y:2}}}); vm.watch('a.b.x ...

随机推荐

  1. 【一天一道LeetCode】#57. Insert Interval

    一天一道LeetCode系列 (一)题目 Given a set of non-overlapping intervals, insert a new interval into the interv ...

  2. 手把手带你画一个动态错误提示 Android自定义view

    嗯..再差1篇就可以获得持之以恒徽章了,今天带大家画一个比较简单的view. 转载请注明出处:http://blog.csdn.net/wingichoy/article/details/504771 ...

  3. centos vsftpd 553 Could not create file解决方法

    centos vsftpd 553 Could not create file解决方法   问题由于selinux引起的,问题解决办法:   www.2cto.com   输入:getsebool - ...

  4. JavaScript进阶(四)js字符串转换成数字的三种方法

    js字符串转换成数字的三种方法 在js读取文本框或者其它表单数据的时候获得的值是字符串类型的,例如两个文本框a和b,如果获得a的value值为11,b的value值为9 ,那么a.value要小于b. ...

  5. Github Coding Developer Book For LiuGuiLinAndroid

    Github Coding Developer Book For LiuGuiLinAndroid 收集了这么多开源的PDF,也许会帮到一些人,现在里面的书籍还不是很多,我也在一点点的上传,才上传不到 ...

  6. STL - stack(栈)

    Stack简介 stack是堆栈容器,是一种"先进后出"的容器. stack是简单地装饰deque容器而成为另外的一种容器. #include <stack> stac ...

  7. 数据cube的schema与sql的对应的关系

    用schema workbench 设置cube的维度结构 saiku 使用的cube,会将不同维度的查询转化为sql语句. schema中, cube的事实表和dimension表进行自然连接,具体 ...

  8. Android回调详解

         很多时候开发遇到一些Ui更新 网络数据获取,或者方法方法传递的时候会借助回调函数,那么什么是回调函数 百度百科是这么解释的  转载请标注出处 http://blog.csdn.net/sk7 ...

  9. Oracle rownum 分页, 排序

    Oracle rownum 分页, 排序 什么是rownum, rownum的生成, rownum相关的符号操作 Rownum是oracle生成结果集时得到的一个伪列, 按照读出行的顺序, 第一条ro ...

  10. 关于SharePoint2007简单随感

    首先,还是要感谢我毕业以后的这第一份正式工作,当然现在也依然在做,带我走进了SharePoint的世界,很奇妙也许是有缘吧,自己不是个努力的人,从面试的时候对Moss这个东西闻所未闻,到现在一知半解, ...