Do I need "self" and "other"?
Gabriel Rossetti
gabriel.rossetti at arimaz.com
Sat Jun 28 14:03:31 EDT 2008
Kurda Yon 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?
>
> Thank you!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
>
The first param "self" in an instance method is a convention, I would
recommend not changing it. The "self" param is pass automatically when
you call the method, like so :
self.method(param)
and this would have been defines as :
def method(self, param):
# do something here
Self is like "this" in java, except it is explicitly added to the
parameter list as the first parameter. You could name it whatever you
want, but python programmers will throw tomatoes at you for naming it
something else :-), since it mean "myself" in if the instance's
perspective. Sometimes you have to pass it explicitly, like when calling
your parent's method, be you'll see this when you study inheritance.
I hope that helps, the "self" param had mixed me up some the first time
I had seen it.
Gabriel
More information about the Python-list
mailing list