0%

Your First Classes and Objects · practice

What self Refers To

The Question class now uses self in both __init__ and is_correct. We have relied on it several times, so this lesson slows down to examine exactly what it refers to.

self is a for the instance receiving the current method call. It can feel unusual because we write it in the method definition but do not supply it explicitly when using the usual dot notation.

Consider two questions:

first = Question("Two plus two?", "4")
second = Question("Three plus three?", "6")

first.is_correct("4")
second.is_correct("4")

During the first call, self refers to first. During the second call, self refers to second.

Python behaves roughly as if the calls were written like this:

Question.is_correct(first, "4")
Question.is_correct(second, "4")

You will normally use the clearer instance form. The expanded form reveals where self comes from.

Calling first.is_correct supplies first as self and the string 4 as response.

The name is a convention with a purpose

Python does not reserve the word self, but Python programmers use it consistently. Keeping that convention makes method definitions readable to everyone.

Inside a method:

  • self.answer means the answer attribute on the current instance;

  • self.prompt means the prompt attribute on the current instance;

  • another method call can use self.some_method().

What does this print?

class Label:
    def __init__(self, text):
        self.text = text

    def show(self):
        print(self.text)

first = Label("A")
second = Label("B")
first.show()
second.show()

The important idea is not that every contains a named self. It does not. self is a method parameter that temporarily refers to the instance receiving that particular call.

Task

Complete answer_length so it returns the length of the current question’s answer.

Then use Step in the exercise editor. Follow the calls for first and second. In each frame, compare self.answer with the returned by len.

If the panel makes the two instances difficult to distinguish, note that as platform feedback rather than guessing what Python did.