when and how do you use Self?

Ron Adam rrr at ronadam.com
Mon Nov 7 17:47:58 EST 2005


Tieche Bruce A MSgt USMTM/AFD wrote:
> I am new to python,
> 
> Could someone explain (in English) how and when to use self?
> 
> I have been reading, and haven't found a good example/explanation
> 
>   
> Bruce Tieche (bruce.tieche at usmtm.sppn.af.mil)


Hi,  Sometimes it's hard to get a simple answer to programming questions 
as everyone sees different parts of the elephant. ;-)


The use of self is needed because methods in class's are shared between 
all the instances (objects created from class's).  Because of this 
sharing, each method in a class needs a name to receive the specific 
instance reference which called it.

If every instance had it's own copy of all the methods in a class, we 
might not need 'self', but our programs would become extreme memory 
hogs. So sharing code is the great benefit of class's.

For example...

class myclass(object):
     def foo(self, a, b):
	self.c = a + b

The method foo is defined but not executed until it is called later from 
an instance.  It's located in the class, but may be called from a lot, 
(thousands or more), different instances made from this class.

bar = myclass()    # create a single instance (object)
                    # and bind it to the name bar.


Then when you do...

bar.foo(1,2)   # converted to ->  myclass(bar, 1, 2)

It calls the 'foo' method located in the parent class and pass's a 
reference to 'bar' as the first argument.  'self' becomes the new name 
for bar within foo.

     self.c = a + b    #  same as ->  bar.c = a + b


This should be enough to visualize the basic relationship.  Hope it helped.

Cheers,
    Ron














More information about the Python-list mailing list