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. python爬虫 - Urllib库及cookie的使用

    http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...

  2. PO订单审批通过API

    DECLARE l_return_status VARCHAR2(1); l_exception_msg VARCHAR2(4000); BEGIN mo_global.set_policy_cont ...

  3. Useful Articles for the Oracle E-Business Suite Technology Stack for Technical Consultant / DBA [ID

    Applies to:  Oracle Applications Technology Stack - Version: 11.5.10.2 to 12.1.3 - Release: 11.5.10 ...

  4. Android群英传笔记——第十章:Android性能优化

    Android群英传笔记--第十章:Android性能优化 随着Android应用增多,功能越来越复杂,布局也越来越丰富了,而这些也成为了阻碍一个应用流畅运行,因此,对复杂的功能进行性能优化是创造高质 ...

  5. Java学习笔记(一)网格袋布局

    网格袋布局类似于Win8的Metro布局,用于将组件按大小比例放在不同位置的网格内,各组件的实际大小会随着窗口的改变而改变,但相对位置不变,能够很好的适应屏幕. 通过阅读<21天学通Java&g ...

  6. 基于GraphCuts图割算法的图像分割----OpenCV代码与实现

    转载请注明出处:http://blog.csdn.net/wangyaninglm/article/details/44151213, 来自:shiter编写程序的艺术 1.绪论 图切割算法是组合图论 ...

  7. linux下播放组播流出现setsockopt:No such device错误

    在linux下播放组播流出现setsockopt:No such device错误是因为多播IP没有add路由表里面 可以采用如下命令完成: root@android:/ # busybox rout ...

  8. ExtJS:GridPanel之renderer:function()和itemdblclick : function()方法参数详解

    要使用GridPanel,首先要定义Store,而在创建Store的时候必须要有Model,因此我们首先来定义Model: Ext.define("Gpsdata", { exte ...

  9. 加载SpriteBuilder中的scene为何不能带后缀

    我们在Xcode中切换SpriteBuilder中的scene时,一般使用的是如下代码: -(void)exitButtonPressed:(CCControl*)sender{ CCLOG(@&qu ...

  10. 软件工程师 Book

    一.软件工程师  --Clean Code<代码整洁之道>  --Implementation Patterns<实现模式>  --Code Complete<代码大全& ...