zoukankan      html  css  js  c++  java
  • python3.4中自定义数组类(即重写数组类)

    '''自定义数组类,实现数组中数字之间的四则运算,内积运算,大小比较,数组元素访问修改及成员测试等功能'''
    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
     array lenghts:%d'%(x,len(x)))
        x = x+2
        print(x.getValue)
  • 相关阅读:
    HTML5 五大特性
    JS DATE对象详解
    MySQL复制错误 The slave I/O thread stopsbecause master and slave have equal MySQL server UUIDs; these UUIDs must bedifferent for replication to work 解析
    MySQL OSC(在线更改表结构)原理
    Mycat基本搭建
    MySQL MVCC原理
    MySQL索引
    MySQL5.7新特性
    mysql报错"ERROR 1206 (HY000): The total number of locks exceeds the lock table size"的解决方法
    监控Mongo慢查询
  • 原文地址:https://www.cnblogs.com/ysq0908/p/9157373.html
Copyright © 2011-2022 走看看