[Tutor] To make a new pyarray class

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


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.

-- 
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