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)
  • 相关阅读:
    web框架基础
    前端基础之DOM和jQuery
    前端基础之JavaScript
    前端基础之CSS
    福州大学W班-助教总结
    福州大学W班-个人最终成绩统计
    福州大学W班-Beta冲刺评分
    福州大学W班-alpha冲刺评分
    福州大学W班-团队作业-随堂小测(同学录)成绩
    福州大学W班-需求分析评分排名
  • 原文地址:https://www.cnblogs.com/ysq0908/p/9157373.html
Copyright © 2011-2022 走看看