[Tutor] Self
Gregor Lingl
glingl at aon.at
Thu Dec 18 02:59:55 EST 2003
Ryan Sheehy schrieb:
>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,
>
>
Hi Ryan!
I'll try to elaborate a bit Danny's example. Suppose you have:
class Person:
def __init__(self, name):
self.name = name
def pat_head(self):
print "I'm", self.name,"and",
print "I'm patting my head"
def rub_stomach(self):
print "I'm", self.name, "and",
print "I'm rubbing my stomach"
## The class Person can be used this way:
>>> danny = Person("Danny")
>>> ryan = Person("Ryan")
>>> danny.rub_stomach()
I'm Danny and I'm rubbing my stomach
>>> ryan.pat_head()
I'm Ryan and I'm patting my head
## We want Danny to play a game and define a function:
>>> def play_game():
danny.pat_head()
danny.rub_stomach()
>>> play_game()
I'm Danny and I'm patting my head
I'm Danny and I'm rubbing my stomach
## But what if Ryan also wants to play the game?
## We can redefine play_game with a parameter,
## so we can pass the person to play to it as
## an argument.
>>> def play_game(somebody):
somebody.pat_head()
somebody.rub_stomach()
>>> play_game(danny)
I'm Danny and I'm patting my head
I'm Danny and I'm rubbing my stomach
>>> play_game(ryan)
I'm Ryan and I'm patting my head
I'm Ryan and I'm rubbing my stomach
## works fine. Now we can make this to
## a method of Person by simply putting it into the
class statement that defines Person:
class Person:
def __init__(self, name):
self.name = name
def pat_head(self):
print "I'm", self.name,"and",
print "I'm patting my head"
def rub_stomach(self):
print "I'm", self.name, "and",
print "I'm rubbing my stomach"
def play_game(somebody):
somebody.pat_head()
somebody.rub_stomach()
## and try it out:
>>> ================================ RESTART
================================
>>> danny = Person("Danny")
>>> ryan = Person("Ryan")
>>> danny.play_game()
I'm Danny and I'm patting my head
I'm Danny and I'm rubbing my stomach
>>> ryan.play_game()
I'm Ryan and I'm patting my head
I'm Ryan and I'm rubbing my stomach
## works fine. Incidentally there is the *convention*
## to call the parameter that points to the object
## it*self* self.
## Alas, Your proposition to use Person.pat_head()
## won't work, as it leaves open who should pat his head.
## But you *can* use a method like a function bound to a class,
## passing the appropriate argument as earlier, like this:
>>> Person.play_game(ryan)
I'm Ryan and I'm patting my head
I'm Ryan and I'm rubbing my stomach
>>>
Hope this makes something more clear for you
Gregor
More information about the Tutor
mailing list