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. Java序列化Serializable和Externalizable

    纸上得来终觉浅,绝知此事要躬行  --陆游       问渠那得清如许,为有源头活水来  --朱熹 什么是Java序列化?为什么出现Java序列化?怎样实现Java序列化? 一.什么是Java序列化 ...

  2. STL - string(典型操作demo)

    1String概念  string是STL的字符串类型,通常用来表示字符串.而在使用string之前,字符串通常是用char*表示的.string与char*都可以用来表示字符串,那么二者有什么区别呢 ...

  3. gdb学习(一)[第二版]

    概述 gdb是GNU debugger的缩写,是编程调试工具. 功能 1.启动程序,可以按照用户自定义的要求随心所欲的运行程序. 2.可让被调试的程序在用户所指定的断点处停住 (断点可以是条件表达式) ...

  4. 【Android 应用开发】Android中使用ViewPager制作广告栏效果 - 解决ViewPager占满全屏页面适配问题

    . 参考界面 : 携程app首页的广告栏, 使用ViewPager实现        自制页面效果图 : 源码下载地址: http://download.csdn.net/detail/han1202 ...

  5. utl_file包的使用

    首先看一下oracle 脚本 /* # $Header: HTMomse12.sql 12.0.4 20121015 Support $ #+============================= ...

  6. Struts2技术内幕 读书笔记一 框架的本质

    本读书笔记系列,主要针对陆舟所著<<Struts2技术内幕 深入解析Strtus2架构设计与实现原理>>一书.笔记中所用的图片若无特殊说明,就都取自书中,特此声明. 什么是框架 ...

  7. TCP连接建立系列 — 服务端发送SYNACK段

    本文主要分析:服务器端如何构造和发送SYNACK段. 内核版本:3.6 Author:zhangskd @ csdn blog 发送入口 tcp_v4_send_synack()用于发送SYNACK段 ...

  8. How tomcat works 读书笔记十四 服务器组件和服务组件

    之前的项目还是有些问题的,例如 1 只能有一个连接器,只能处理http请求,无法添加另外一个连接器用来处理https. 2 对容器的关闭只能是粗暴的关闭Bootstrap. 服务器组件 org.apa ...

  9. 通信录列表+复杂Adapter分析

    概述 最近写论文之余玩起了github,发现有个citypicker挺不错的,高仿了美团城市选择和定位的一些功能 地址链接 效果图如下: 自己手动写了一遍优化了一些内容,学到了一些姿势,下面对其中一些 ...

  10. linux下如何查询未知库所依赖的包

    经常会遇到linux下安装软件时提示少文件,如何知道所缺少的文件属于哪个包?用什么命令查看? 例如:/lib/ld-linux.so.2: bad ELF interpreter: 没有那个文件或目录 ...