[Tutor] Self

Ryan Sheehy the_investor at arach.net.au
Wed Dec 17 21:35:37 EST 2003


Thanks Todd and Danny!

Danny:

Okay... 'self' is required if calls need to be made to methods and functions
that reside in the same class. Is that right?

If so, could the call 'Person.pat_head()' still give the same result in the
play_game method?

Thanks,


Ryan

-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu]
Sent: Thursday, 18 December 2003 9:56 AM
To: Ryan Sheehy
Cc: tutor at python.org
Subject: Re: [Tutor] Self




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!


---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003




More information about the Tutor mailing list