What is "self"?

Ron Adam rrr at ronadam.com
Thu Sep 22 22:10:42 EDT 2005


Wayne Sutton wrote:
> 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 plain english?
> 
> Thanks,
> Wayne 


I'll give it a try..

When you have a class definition:

     class Person(object):
         def set_name(self, name):
             self.name = name

The method "set_name", has no idea what your class instance is going to 
called at this point.  But it will need to know when it's called.  So 
for now "self" is just a argument waiting to be assigned a reference 
later just like any other function argument. You can actually call it 
anything you want but "self" is sort of a tradition.

     leader = Person()

This creates an instance of your class and stores a reference to it in 
the name "leader".  Now that that you have an instance with a name.  You 
can use your class method to do something.

     leader.set_name("John")

When you call a method of an instance, Python translates it to...

     leader.set_name(leader, "John")

So "self" in your method definition gets assigned a reference to 
"leader".  "self" can then be used to access the other values and 
methods stored in your class instance.  Or in this case store a value in 
your class instance.  Basically "self" becomes a reference to the class 
instance it is in.

     self.name = name

is the same as ...

     leader.name = name

But we didn't know it was going to be called "leader" when we wrote the 
class.  So self is a convienent place holder.


I hope this helped.

Cheers,
Ron












More information about the Python-list mailing list