Do I need "self" and "other"?

Maric Michaud maric at aristote.info
Sat Jun 28 05:09:29 CEST 2008


Le Saturday 28 June 2008 00:17:33 Kurda Yon, vous avez écrit :
> class Vector:
>   def __add__(self, other):
>     data = []
>     for j in range(len(self.data)):
>       data.append(self.data[j] + other.data[j])
>     return Vector(data)
>
> In this example one uses "self" and "other". Does one really need to
> use this words?

Yes, he does, because one really need to follow the conventions of a language, 
which belong to the language even they don't belong to its syntax. You should 
have a look to the PEP 8 : http://www.python.org/dev/peps/pep-0008/

self is the good name for the implicit argument of instancemethod.
other is the name widely used for rvalue in binary operators definition.

As for convention, your constructor, Vector(iterable), is expected to be a 
copy constructor, that means the Vector's __init__ method is somewhat like 
this :

def __init__(self, iterable=()) :
    self.data=list(iterable) # create a copy of the parmeter

First, self.data should be renamed to self._data, see PEP 8 for details, 
because data will probably not be part of the API of your object.

Then, this make your code a bit curious, you create a list to add the two 
vectors, then copy it to create the resultiing vector, consuming two times 
the memory needed.

Finally, you would probably gain in inheriting directly from the builtin type 
list.

Here is my proposal for your Vector class (wth some other enhancements) :

class Vector(list) :

def __init__(self, iterable=()) :

    def __init__(self, iterable=()) :
        list.__init__(self, iterable)

    def __repr__(self) :
        return 'Vector(%s)' % list.__repr__(self)

    def __add__(self, other) :
        res = Vector()
        for i, elt in enumerate(self) :
            res.append(elt + other[i])
        return res

Note that I don't know how you want to deal vectors of different dimensions, 
you should probably raise a ValueError.

Also use enumerate, "i in xrange(len(iterable))" was required before enumerate 
was done a builtin but is rather ugly.

Finally, to come to a more functionnal style the method could have been 
written like this :

from itertools import izip

...

    def __add__(self, other) :
        return Vector(x + y for x, y in izip(self, other))



-- 
_____________

Maric Michaud



More information about the Python-list mailing list