Do I need "self" and "other"?
David C. Ullrich
dullrich at sprynet.com
Mon Jun 30 16:09:45 EDT 2008
In article
<68566b52-100d-40ee-a0c6-bde20df9ecd4 at a70g2000hsh.googlegroups.com>,
Kurda Yon <kurdayon at yahoo.com> wrote:
> Hi,
>
> I found one example which defines the addition of two vectors as a
> method of a class. It looks like that:
>
> 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? And, if yes, why? I have replaced "self" by "x" and
> "other" by "y" and everything looks OK. Is it really OK or I can have
> some problem in some cases?
What everyone else has said: yes and no.
Having said that, it seems to me like this is exactly the sort
of situation where 'x' and 'y' make a lot of sense - self means
that this is the object on which the method was invoked, and
here that seems irrelevant: If you want to calculate x + y
you use x.data and y.data...
Otoh, I once saw a library (someone's Python arbitrary-precision
reals package) where he used x and y, and sure enough I was
confused.
Otooh, I was't confused by it for long, and I quickly decided
that it actually made _that_ code look like it made more sense.
> Thank you!
--
David C. Ullrich
More information about the Python-list
mailing list