python_重写数组
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_重写数组的更多相关文章
- Vue2.0响应式原理以及重写数组方法
// 重写数组方法 let oldArrayPrototype = Array.prototype; let proto = Object.create(oldArrayPrototype); ['p ...
- python3.4中自定义数组类(即重写数组类)
'''自定义数组类,实现数组中数字之间的四则运算,内积运算,大小比较,数组元素访问修改及成员测试等功能''' class MyArray: '''保证输入值为数字元素(整型,浮点型,复数)''' de ...
- Python_重写集合
class Set(object): def __init__(self,data=None): if data == None: self.__data = [] else: if not hasa ...
- ES6数组扩展
前面的话 数组是一种基础的JS对象,随着时间推进,JS中的其他部分一直在演进,而直到ES5标准才为数组对象引入一些新方法来简化使用.ES6标准继续改进数组,添加了很多新功能.本文将详细介绍ES6数组扩 ...
- 数组中的each 和 jquery 中的 each
数组的实例上都有一个叫做 forEach 的方法,这个方法定义在 Array.prototype 上,所以数组的所有实例都可以使用 forEach 这个方法. forEach 方法的语法结构如下: v ...
- ES里关于数组的拓展
一.静态方法 在ES6以前,创建数组的方式主要有两种,一种是调用Array构造函数,另一种是用数组字面量语法,这两种方法均需列举数组中的元素,功能非常受限.如果想将一个类数组对象(具有数值型索引和le ...
- 迷你MVVM框架 avalonjs1.5 入门教程
avalon经过几年以后,已成为国内一个举足轻重的框架.它提供了多种不同的版本,满足不同人群的需要.比如avalon.js支持IE6等老旧浏览器,让许多靠政府项目或对兼容性要求够高的公司也能享受MVV ...
- 230行实现一个简单的MVVM
作者:mirone链接:https://zhuanlan.zhihu.com/p/24451202来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. MVVM这两年在前端届 ...
- 谈谈数据监听observable的实现
一.概述 数据监听实现上就是当数据变化时会通知我们的监听器去更新所有的订阅处理,如: var vm = new Observer({a:{b:{x:1,y:2}}}); vm.watch('a.b.x ...
随机推荐
- 09_Android中ContentProvider和Sqllite混合操作,一个项目调用另外一个项目的ContentProvider
1. 编写ContentPrivider提供者的Android应用 清单文件 <?xml version="1.0" encoding="utf-8"? ...
- 3、使用Gradle创建Libgdx项目
(原文链接:http://www.libgdx.cn/topic/20/3-%E4%BD%BF%E7%94%A8gradle%E5%88%9B%E5%BB%BAlibgdx%E9%A1%B9%E7%9 ...
- mysql进阶(五)数据表中带OR的多条件查询
MySQL数据表中带OR的多条件查询 OR关键字可以联合多个条件进行查询.使用OR关键字时: 条件 1) 只要符合这几个查询条件的其中一个条件,这样的记录就会被查询出来. 2) 如果不符合这些查询条件 ...
- TrueType和Bitmap字体的区别
只要标签的文本从不变化,在cocos2D中渲染TrueType和bitmap字体的性能是相同的.它们都仅仅像精灵那样绘制. 如果你希望大量的标签使用相同字体,则bitmap字体将更快.因为bitmap ...
- 网站开发进阶(二十三)Address already in use: JVM_Bind <null>:8088
Address already in use: JVM_Bind <null>:8088 注:请点击此处进行充电! 阿里云服务器又莫名其妙的宕掉!内存泄漏问题依然存在,又出现了端口占用的情 ...
- Leetcode_48_Rotate Image
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/44216867 You are given an n x n ...
- Java基本数据类型和长度
转自:http://lysongfei.iteye.com/blog/602546 java数据类型 字节 表示范围 byte(字节型) 1 -128-127 short(短整型 ...
- SpriteBuilder中物理对象能否被缩放
我前面早些时候提到物理形状不能被缩放. 现在我却说可以缩放它们,这是为啥呢? 好吧,拥有物理物体节点的缩放属性真心不能被动画化或改变在运行的时候; 但是你可以在SpriteBuilder中设置启用物理 ...
- ORALCE EBS ALERT 初体验
Oracle EBS Alert Alert 是一种Oracle系统中的一种机制,它可以监视系统数据库,在规定的情况下给规定用户一个通知,通知可以是邮件或者其他形式,在标注的系统和客户化系统中都是可以 ...
- LeetCode之旅(15)-Odd Even Linked List
题目描述: Given a singly linked list, group all odd nodes together followed by the even nodes. Please no ...