__iadd__ for a subclass of array - howto

Helmut Jarausch jarausch at igpm.rwth-aachen.de
Mon Aug 5 03:34:39 EDT 2013


Hi,

I'd like to subclass array.array and implement operators like __iadd__
How can this be accomplished.

I'tried

from array import array

class Vec(array) :
  def __new__(cls,Vinit) :
    return array.__new__(cls,'d',Vinit)

  def __init__(self,*args) :
    self.N = len(self)

  def __str__(self) :
    out=[ "{}".format(self.__getitem__(i)) for i in range(0,self.N) ]
    return ",".join(out)
    
  def __iadd__(self,Op) :
#    for i,x in enumerate(self) :
#      x+= Op[i]                     # this doesn't update self
    for i in range(0,self.N) :
      (self.__getitem__(i))+= Op[i]  # __getitem__ doesn't return a "reference" (like in C++)
    return self


Many thanks for a hint,
Helmut



More information about the Python-list mailing list