473,486 Members | 2,429 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Do I need "self" and "other"?

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!
Jun 27 '08 #1
13 11981
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?
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.

--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
Jun 27 '08 #2
On Jun 27, 6:32 pm, Hans Nowak <zephyrfalcon!NO_SP...@gmail.com>
wrote:
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?

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.

--
Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/
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.
Jun 27 '08 #3


Kurda Yon wrote:
>

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

Jun 27 '08 #4
Terry Reedy wrote:
>
Kurda Yon wrote:
>>
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.
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

Jun 28 '08 #5
On Friday 27 June 2008 06:41:22 pm Kurda Yon wrote:
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,

--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
Jun 28 '08 #6
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

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!
In Python, when defining the methods of a class, you pass self as an
argument to these methods so that they can have access to the class's
variables and methods.

Example:

class Foo():
self.x = 5

def bar(self):
print self.x

def baz():
print self.x #This raises an error.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkhlg3QACgkQLMI5fndAv9gQZgCfRV15fQwGb9 +n7Lz6JYmfXdeZ
0fYAn0fK90XfR7in/B9TjflwBRFcsgSS
=qyXG
-----END PGP SIGNATURE-----
Jun 28 '08 #7
In article
<68**********************************@a70g2000hsh. googlegroups.com>,
Kurda Yon <ku******@yahoo.comwrote:
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.
Jun 28 '08 #8
In article
<04**********************************@p25g2000hsf. googlegroups.com>,
Kurda Yon <ku******@yahoo.comwrote:
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.
Jun 28 '08 #9
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
Jun 28 '08 #10
On Fri, 27 Jun 2008 20:19:00 -0400, Nick Dumas <dr******@gmail.comwrote:
[snip]
>
Example:

class Foo():
self.x = 5

Have you tried what you're posting?

Python 2.4.3 (#2, Oct 6 2006, 07:52:30)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>class Foo():
File "<stdin>", line 1
class Foo():
^
SyntaxError: invalid syntax
>>class Foo( object ):
.... self.x = 5
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in Foo
NameError: name 'self' is not defined
>>>
--
To email me, substitute nowhere->spamcop, invalid->net.
Jun 28 '08 #11
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Peter Pearson wrote:
On Fri, 27 Jun 2008 20:19:00 -0400, Nick Dumas <dr******@gmail.comwrote:
[snip]
>Example:

class Foo():
self.x = 5


Have you tried what you're posting?

Python 2.4.3 (#2, Oct 6 2006, 07:52:30)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>class Foo():
File "<stdin>", line 1
class Foo():
^
SyntaxError: invalid syntax
>>>class Foo( object ):
.... self.x = 5
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in Foo
NameError: name 'self' is not defined
Yeah, looking back at that...bleh. Not a smart typo. But I did run the
- -proper- code, and I learned a little bit about Python and classes.
Sorry for the typo, folks.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkhmfB8ACgkQLMI5fndAv9gAWgCcDjDIVhHAHD T4r/K8iPqoJALv
HRIAnRgT5KELazbf42Y3084zwQlZ/fJt
=vE7Z
-----END PGP SIGNATURE-----
Jun 28 '08 #12
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

Jun 28 '08 #13
In article
<68**********************************@a70g2000hsh. googlegroups.com>,
Kurda Yon <ku******@yahoo.comwrote:
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
Jun 30 '08 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2416
by: Todd Gardner | last post by:
Pardon my extremely ignorant newbie questions. Where can I go to find more information about the "self" argument? Is there something special about the word "self" or did Mr. Guido van Rossum...
5
2809
by: BJörn Lindqvist | last post by:
I think it would be cool if you could refer to instance variables without prefixing with "self." I know noone else thinks like me so Python will never be changed, but maybe you can already do it...
3
1720
by: Anthony Liu | last post by:
I want to use the set function like mylist = myset = set (mylist) But I don't know what to import, I tried sys, sets, they don't work. What's the easy way to find out the module that...
26
2144
by: Fernando M. | last post by:
Hi, i was just wondering about the need to put "self" as the first parameter in every method a class has because, if it's always needed, why the obligation to write it? couldn't it be implicit?...
20
2827
by: Wayne Sutton | last post by:
OK, I'm a newbie... I'm trying to learn Python & have had fun with it so far. But I'm having trouble following the many code examples with the object "self." Can someone explain this usage in...
9
2729
by: shannonl | last post by:
Hi all, For some reason this bind is calling the donothing function, like it should, but is then allowing the text to be inserted into the Text widget. Here is the code: ...
9
2179
by: Emanuele Aina | last post by:
I have some code which does a lot of "in" on lists containing objects with no __eq__ defined. It all goes fast until I add the __lt__() method: then I have a slowdown comparable to the one I get...
17
2748
by: David C. Ullrich | last post by:
Having a hard time phrasing this in the form of a question... The other day I saw a thread where someone asked about overrideable properties and nobody offered the advice that properties are...
8
2683
by: ssecorp | last post by:
I first learned about OO from Java. I much prefer to program in Python though. However I am consufed about 2 things. 1. Why do I have to pass self into every method in a class? Since I am...
0
7105
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6967
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7180
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6846
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5439
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4870
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3076
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3071
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
266
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.