python定义整数数组,python基础教程之Python自定义一个数组类,支持数

class MyArray:

'''保证输入的内容是整型、浮点型'''

def ___isNumber(self, num):

if not isinstance(num, (int,float)):

return False

return True

#开始写构造函数,接受可变长度的数组

def __init__(self, *args):

if args == None:

self.__value = []

else:

for a in args:

if not self.___isNumber(a):

print('All elements must be number!')

#self.__value 是一个数组

self.__value = list(args)

#打印输出当前的self.__value

def printSelf(self):

#这个self是一个地址

print(self)

#这个self.__value是一个数组

print(self.__value)

#重载len(Array)这个方法

def __len__(self):

return len(self.__value)

#append方法

def append(self, other):

self.__value.append(other)

#注意:此处不能够直接return self.__value.append(other)

#这个方法执行后没有返回值

return self.__value

#重载运算符+

def __add__(self,other):

if self.___isNumber(other):

#如果other 是一个数,则数组里每一个元素都加上other

array = MyArray()

array.__value = [ i + other for i in self.__value]

return array.__value

elif isinstance(other,MyArray):

#如果other 是一个数组,则两个数组对应位置的数相加

if (len(self.__value) == len(other.__value)):

array = MyArray()

array.__value = [i+j for i,j in zip(self.__value,other.__value)]

return array.__value

else:

print('The size must be equal!')

else:

print('Please input a array or a num!')

#重载运算符 / 浮点数除法,返回浮点数

def __truediv__(self,other):

if self.___isNumber(other):

if other == 0:

print("Zero cant be this number!")

return

array = MyArray()

array.__value = [i / other for i in self.__value]

return array.__value

else:

print("It is must be a number except zero!")

#重载运算符 // 整数除法,返回不大于结果的最大的一个整数

def __floordiv__(self,other):

if isinstance(other,int):

if other == 0:

print("Zero cant be this number!")

return

array = MyArray()

array.__value = [i // other for i in self.__value]

return array.__value

else:

print("Tt is must be a number except zero!")

#重载运算符% 取余数

def __mod__(self,other):

if isinstance(other,int):

if other == 0:

print("Zero cant be this number!")

return

array = MyArray()

array.__value = [i % other for i in self.__value]

return array.__value

else:

print("Tt is must be a number!")

#根据数组index查看元素

def __getitem__(self,index):

arrayLength = len(self.__value)

if isinstance(index,int) and (0 <= index <= arrayLength):

return self.__value[index]

else:

print("Index must be a Inteager which is less than", arrayLength-1)

#查看元素是否在该列表

def __contains__(self,other):

if other in self.__value:

return True

return False

#数组比较

def __lt__(self,other):

if not isinstance(other,MyArray):

print("It is must be the type of MyArray")

return False

if self.__value < other.__value:

return True

return False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值