when and how do you use Self?

Alex Martelli aleax at mail.comcast.net
Fri Nov 4 00:13:12 EST 2005


Tieche Bruce A MSgt USMTM/AFD <bruce.tieche at usmtm.sppn.af.mil> wrote:
   ...
> I am new to python,
> Could someone explain (in English) how and when to use self?

A class's methods use 'self' to refer to the object (instance of the
class) they're being called on; mostly, they access (get or set)
attributes on self, and/or call other methods on self.

I hope that's English enough for you.  Here's a simple example:

class Struggle(object):
    def __init__(self, value): self.value = value
    def __str__(self): return 'Struggle(%r)' % self.value

Class Struggle has two (special) methods, an initializer and a
transformer to string.  Each uses 'self' to refer to the instance on
which it's being called -- specifically, to set or get the 'value'
attribute.  So, when I code:

x = Struggle(23)
print x

I obtain the output:

Struggle(23)

In this case, the 'self' inside each method refers to the same object to
which the name 'x' refers ``on the outside''.


Alex



More information about the Python-list mailing list