[Tutor] Get confused by self

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Sep 24 03:08:33 CEST 2004



On Thu, 23 Sep 2004, W X Liu wrote:

> I am learning the class section for Python, but I get confused by self,
> what does it really mean?


Hello!


Here's a small example that might help clear things up.



Let's say that we have a few people around:

###
>>> yoo = {'name': 'Danny', 'friends':[]}
>>> liu = {'name': 'Wenxin', 'friends': []}
###

I'm being a bit informal here: I'm just representing a "person" as a
dictionary.  Please ignore the fact that I'm not technically using classes
for the moment.  *grin*  We'll get to that in the end.



Maybe we might want to make it easier to make more people; when I make a
new person, I could accidently mistype the 'friends' as 'freinds', and
that would be tragic.  Let's write a small function to make that mistake
less likely:

###
>>> def makePerson(name):
...     return {'name': name, 'friends': []}
...
>>> andrews = makePerson('Rob')
>>> andrews
{'friends': [], 'name': 'Rob'}
###


Ok, so now we have these three people: 'liu', 'andrews', and 'yoo'.  We
can have these three people greet each other as friends:

###
>>> def greetFriends(person):
...     for f in person['friends']:
...         print 'hello', f
...
>>> greetFriends(liu)
>>>
###


But 'liu' has an empty list of friends!  Ok, lets make another function to
add a friend to any person:


###
>>> def addFriend(person, other):
...     person['friends'].append(other)
...
>>> addFriend(liu, yoo)
>>> addFriend(liu, andrews)
>>> greetFriends(liu)
hello {'friends': [], 'name': 'Danny'}
hello {'friends': [], 'name': 'Rob'}
###


That looks a little funky: let's get greetFriends() to just print out the
name of the other folks.  We can make it easier to grab the name of a
person by adding a getName() function.  Oh, at the same time, let's make
it easier to get the friends of a person with a getFriends() function:

###
>>> def getName(person):
...     return person['name']
...
>>> def getFriends(person):
...     return person['friends']
...
###



Once we have these two helper functions, now we can rewrite
greetFriends():


###
>>> def greetFriends(person):
...     for f in getFriends(person):
...         print "hello", getName(f)
...
###


And now let's see what happens when we call greetFriends() on liu:

###
>>> greetFriends(liu)
hello Danny
hello Rob
###

That looks nicer.  *grin*



Ok, the punchline here is that all that we've been doing about is pretty
much what 'classes' do.  Python's classes do more, but the core of it is
what we've been doing above, with a bit more syntax support from Python.


Remember that we wrote this:

###
def makePerson(name):
    """A constructor for a person."""
    return {'name': name, 'friends': []}

def getName(person):
    """Gets the name of a person."""
    return person['name']

def getFriends(person):
    """Gets the friends of a person."""
    return person['friends']

def greetFriends(person):
    """Sends a warm greeting to all of the person's friends."""
    for f in getFriends(person):
        print "hello", getName(f)
###



Here's what that would look like, if we use Python's class notation:


###
class Person:

    def __init__(self, name):
        """An initializer for a person."""
        self.name, self.friends = name, []

    def getName(self):
        """Gets the name of a person."""
        return self.name

    def getFriends(self):
        """Gets the friends of a person."""
        return self.friends

    def greetFriends(self):
        """Sends a warm greeting to all of the person's friends."""
        for f in self.getFriends():
            print "hello", f.getName()
###

The main difference is that 'self' in the class definition plays the role
of the 'person' that we had used to store a person's name and friends.



Does this make sense so far?



More information about the Tutor mailing list