Do I need "self" and "other"?

Nick Dumas drakonik at gmail.com
Fri Jun 27 20:19:00 EDT 2008


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



More information about the Python-list mailing list