[Tutor] Self
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Wed Dec 17 20:56:06 EST 2003
On Thu, 18 Dec 2003, Ryan Sheehy wrote:
> Could someone please explain to me why the call 'self' is needed in
> methods and functions?
>
> I'm having difficulty trying to understand it.
Hi Ryan,
Let's use a concrete example. Let's say we have a Person:
###
class Person:
def pat_head(self):
print "I'm patting my head"
def rub_stomach(self):
print "I'm rubbing my stomach"
###
Let's say that we'd like to add one more method to this Person, some way
of telling the person to both rub its head and stomach sequentially:
###
class Person:
def pat_head(self):
print "I'm patting my head"
def rub_stomach(self):
print "I'm rubbing my stomach"
def play_game(self):
self.pat_head()
self.rub_stomach()
###
Ok, the pieces are set. *grin*
What happens if there aren't any 'self' parameters being passed around?
Let's imagine it:
###
class BadPerson:
"""Note: this class will not work."""
def pat_head():
print "I'm patting my head"
def rub_stomach():
print "I'm rubbing my stomach"
def play_game():
pat_head() ## ??
rub_stomach() ## ??
###
The first two methods might look ok still, but what about the third? The
commented lines with the '??' should draw our attention: what in
particular is trying to pat_head() and rub_stomach()? Nothing is, so this
is syntactically weird --- Just from inspection, this doesn't look like a
method call in Python.
(Note: if you're coming from a language like C++ or Java, you may be
wondering what happened to 'this'. Python does not have any support for
'this', but instead opts for a more explicit model of passing 'self'
around.)
Without a way of accessing the instance, there's no way of writing methods
that themselves call other methods on the same instance. So having 'self'
around lets us write things like play_game(). Does this make sense so
far?
Good luck to you!
More information about the Tutor
mailing list