Python · Stage 9 – Intro to Objects · Lesson 47 of 50

What Is self?

Understand how a method refers to the particular object receiving the call.

Two objects can use the same method but have different attributes. Self tells the method which object is currently involved.

class Dog:
    def __init__(self, name):
        self.name = name

    def introduce(self):
        print(self.name)
Line-by-line explanation
  1. The constructor stores a name on the current object.
  2. Introduce receives the current object as self.
  3. self.name reads that object’s own name.
first = Dog("Milo")
second = Dog("Luna")
second.introduce()
Line-by-line explanation
  1. Two separate objects are created.
  2. Each has its own name.
  3. Calling second’s method displays Luna.

Tiny Practice

Complete the method so it displays this object’s title.

Starter template

class Book:
    def show(self):
        print(CHANGE_ME)
Line-by-line explanation
  1. Show receives the current object.
  2. The desired attribute is title.
Hint
  1. Begin with self.
  2. Use a dot.
  3. Do not quote the attribute name.
Show Solution
class Book:
    def show(self):
        print(self.title)
Line-by-line explanation
  1. Self refers to the current Book.
  2. self.title reads its attribute.
  3. Print displays that value.