Do I need "self" and "other"?

K

Kurda Yon

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

Hans Nowak

Kurda said:
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?

You can use whichever (valid) names you want, but in general 'self' and 'other'
are used for clarity. In this case, they indicate the vector that is operated
on ("self") and another vector ("other"). Using 'x' and 'y' would be less clear
here.
 
K

Kurda Yon

Kurda said:
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?

You can use whichever (valid) names you want, but in general 'self' and 'other'
are used for clarity. In this case, they indicate the vector that is operated
on ("self") and another vector ("other"). Using 'x' and 'y' would be less clear
here.

OK, I see. In the given example "self" is just a name which can be
replace by whichever (valid) name. Is that always like that? I mean,
does "slef" have a special meaning in some cases or it is always "just
a name like any other"? I am asking that because "self" is highlighted
in my text editor, so I assume that it can have a special meaning. I
also heard that "self" refers to a object and I am not sure what that
"refers" means.
 
T

Terry Reedy

Kurda said:
OK, I see. In the given example "self" is just a name which can be
replace by whichever (valid) name. Is that always like that? I mean,
does "slef" have a special meaning in some cases or it is always "just
a name like any other"?

Yes.

A method is a function bound to a class or instance thereof.
Def statements create functions. Parameter names are arbitrary, as long
as they do not conflict with any global names you want to access from
within the function.

Self (and other) are simply community conventions. They do have they
advantage that if they are only used as function/method parameter names,
then they will not conflict with any module globals.

tjr
 
R

Robert Kern

Terry said:
Yes.

A method is a function bound to a class or instance thereof.
Def statements create functions. Parameter names are arbitrary, as long
as they do not conflict with any global names you want to access from
within the function.

Self (and other) are simply community conventions. They do have they
advantage that if they are only used as function/method parameter names,
then they will not conflict with any module globals.

It's worth noting that 'self' for the first parameter of a method is an
extremely strong convention. I highly encourage you to follow it. In particular,
classmethods and staticmethods don't take an instance of the class as the first
argument, so using 'self' for instance methods, 'cls' for classmethods, and
nothing in particular for staticmethods (since the first argument isn't special
at all), helps distinguish them when reading. You risk annoying your reader by
using something other than 'self' in an instance method.

By contrast, using 'other' for the other argument to a binary __mathoperation__
method is not a particularly strong convention. No one will be annoyed if you
use something else.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
L

Luis Zarrabeitia

OK, I see. In the given example "self" is just a name which can be
replace by whichever (valid) name. Is that always like that? I mean,
does "slef" have a special meaning in some cases or it is always "just
a name like any other"? I am asking that because "self" is highlighted
in my text editor, so I assume that it can have a special meaning. I
also heard that "self" refers to a object and I am not sure what that
"refers" means.

It's a name, like any other.
It only has special meaning on the minds of most python programmers. That name
is used, by convention (and only because of convention) to refer the the ...
erm... 'self' object.

That said, of all python conventions, it is perhaps the one most zealously
followed. That's why your editor highlights it.

So, code will not break if you use any other valid name instead of self. But
you shouldn't. Everything will work perfectly - except the readability.

Cheers,
 
R

Roy Smith

Kurda Yon said:
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?

Technically, Python doesn't care what you call them. You could write:

def __add__(luxury_yacht, throat_warbler_mangrove):
etc, etc, etc

and it would run exactly the same. That being said, don't do that. The
use of "self" and "other" are pretty much de rigueur. Experienced Python
programers will instantly understand what they mean. If you use anything
else, they will have to spend more time trying to understand your code.
 
R

Roy Smith

Kurda Yon said:
OK, I see. In the given example "self" is just a name which can be
replace by whichever (valid) name. Is that always like that? I mean,
does [self] have a special meaning in some cases or it is always "just
a name like any other"?

It has absolutely no special meaning. Use of the name "self" is pure
convention.
I am asking that because "self" is highlighted
in my text editor, so I assume that it can have a special meaning.

I use emacs, and the Python mode in emacs highlights it too, as if it were
a keyword. But, that's just an external tool, which is free to do whatever
it wants.
 
M

Maric Michaud

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

Gabriel Rossetti

Kurda said:
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!
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,281
Latest member
Pedroaciny

Latest Threads

Top