[Tutor] To make a new pyarray class

Alan Gauld alan.gauld at yahoo.co.uk
Thu Sep 2 05:03:36 EDT 2021


On 02/09/2021 09:13, Peter Otten wrote:
> 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.

Given the OPs definition of add (adding an integer to every member) I
guess it's really __iadd__() he should be overriding.

I agree if you were adding two pyarray objects(or similar) together
you'd need to return a new object.

To the OP: have you considered what happens if you want to add
multiple values not just one integer? Can you, for example, have
a pyarray of [1,2,3] and add to it [2,3,4] to yield [3,5,7], say?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list