python运算符重载实例

#-*-encoding:utf-8-*-

"""
向量运算
todoList:
1>向量的数乘、数除需要添加左乘、左除
"""

class vector(object):

  def __init__(self, param=[]):
    """
    >>> NoneListTest=vector([])
    >>> IntTest=vector(1)
    >>> FloatTest=vector(-1.1)
    >>> StrTest=vector("")
    >>> OtherTest=vector((1,2,3))
    Traceback (most recent call last):
        ...
    TypeError: Input Param Error
    """
    if not param:
      self._data = []
    #仅接受列表作为参数,如果不是列表切不是单个元素则报错
    elif type(param) == type([]):
      self._data = param
    elif type(param) in [type(1), type(0.1), type('')]:
      self._data = [param]
    else:
      raise TypeError("Input Param Error")
 
  def __len__(self):
    """
    返回向量长度
    >>> SingleElementTest=vector(1)
    >>> len(SingleElementTest)
    1
    >>> MulElementsTest=vector([1,2,3,4,5])
    >>> len(MulElementsTest)
    5
    """
    return(len(self._data)) 
   
  def __str__(self):
    """
    打印向量
    """
    return(str(self._data))
 
  def __add__(self, anotherVector):
    """
    计算加法
    >>> vector1=vector([1,2,3])
    >>> vector2=vector([1,2])
    >>> vector1+vector2
    Traceback (most recent call last):
        ...
    RuntimeError: The tow vectors have different length
    >>> vector2=vector([2,3,4])
    >>> print(vector1+vector2)
    [3, 5, 7]
    >>> vector2=vector([1,2,""])
    >>> print(vector1+vector2)
    Traceback (most recent call last):
        ...
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    """
    if len(self) != len(anotherVector):
      raise RuntimeError("The tow vectors have different length")
    else:
      return(vector([self._data[i] + anotherVector._data[i] for i in range(len(self))]))
  
  def __sub__(self,anotherVector):
    """
    计算减法
    >>> vector1=vector([1,2,3])
    >>> vector2=vector([1,2])
    >>> print(vector1-vector2)
    Traceback (most recent call last):
        ...
    RuntimeError: The tow vectors have different length
    >>> vector2=vector([2,3,4])
    >>> print(vector1-vector2)
    [-1, -1, -1]
    >>> vector2=vector([1,2,""])
    >>> print(vector1-vector2)
    Traceback (most recent call last):
        ...
    TypeError: unsupported operand type(s) for -: 'int' and 'str'
    """
    if len(self) != len(anotherVector):
      raise RuntimeError("The tow vectors have different length")
    else:
      return(vector([self._data[i] - anotherVector._data[i] for i in range(len(self))]))

  def __mul__(self,number):
    """
    计算乘法
    >>> vector1=vector([1,2,3])
    >>> print(vector1*2)
    [2, 4, 6]
    >>> print(vector1*1.5)
    [1.5, 3.0, 4.5]
    """ 
    return(vector([i*number for i in self._data]))
 
  def __truediv__(self,number):
    """
    计算除法
    >>> vector1=vector([1,2,3])
    >>> print(vector1/2)
    [0.5, 1.0, 1.5]
    >>> print(vector1/0)
    Traceback (most recent call last):
        ...
    ZeroDivisionError: int division or modulo by zero
    """
    return(self*(1/number))
 
if __name__ == '__main__':
  import doctest
  doctest.testmod()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值