[Tutor] Get confused by self
Barry Tice
python at pointcontrol.com
Fri Sep 24 01:05:18 CEST 2004
Perhaps an analogy would help.
Consider that you and I are both instances of the class Person. In
python, I might be:
barry = Person("male")
Now, any method or function that I do has to know who it is I'm doing it
to.
Perhaps my Person class looks like this:
class Person:
def __init__(self, whatGender):
self.gender = whatGender
hand = BodyPart("hand")
face = BodyPart("face")
def washFace(self):
# code here to wash a face
self.hand.getSoap()
self.hand.getWetWashcloth()
self.hand.scrubFace(self.face)
# etc.
If I need to wash my face, I can use this:
barry.washFace()
the washFace method has to know whose face is being washed. It also
provides a way to refer to all the component parts of the current object
(Person) and not get them confused with the component parts of another
person object. This way, I'm explicitly washing my own face and not
someone else's.
In this example, self refers to me, so self.hand is MY hand, and
self.face is MY face, and self.gender is MY gender.
Outside of the object itself, those would all be barry.face and
barry.hand and barry.gender, but from within the object, which doesn't
know what name it's going to be going by, they're all just referred to
as self.
In other situations, there may be functions within my Person class that
do something to another object unrelated to me. It may have this
function, for example:
def openDoor(self, door):
door.open()
In this case, the door is the only thing we really care about, so the
self variable isn't used. (It still has to be there, though.) But in a
more elaborate function, it might be:
def openDoor(self, door):
self.hand.turn(door.doorknob)
self.hand.pull(door.doorknob)
In this case, we use the self variable to refer to the Person object
being asked to perform the action, so we can get access to that Person
object's hand component to do the work.
Does this help any?
-- Barry Tice
On Thu, 2004-09-23 at 15:54, W X Liu wrote:
> I am learning the class section for Pyhton, but I get confused by self, what
> does it really mean?
>
> Wenxin
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list