[Tutor] To make a new pyarray class

Peter Otten __peter__ at web.de
Thu Sep 2 04:13:33 EDT 2021


On 02/09/2021 09:11, Alan Gauld via Tutor wrote:
> On 01/09/2021 17:07, Manprit Singh wrote:
> 
>> Other than this if i need a  + operator to be overloaded for this class, +
>> operator should add a scalar value (v) to each element of the instance of
>> this class. Like if an instance of class pyarray is x = [2, 5, 9] then  x+1
>> must produce and return  [3, 6, 10].
>>
>> class pyarray(list):
>>       def __init__(self, *args):
>>           list.__init__(self, args)
>>       def __add__(self, x):
>>           return pyarray(*(ele+x for ele in self))
> 
> Since lists are mutable why not just increment the existing
> pyarray objects?
> 
> for idx,el in enumerate(self):
>      self[idx] += x
> return self
> 
> Just a thought.

For __iadd__()/+= that would be OK, but for __add__()/+ mutating the 
original object is a no-go.







More information about the Tutor mailing list