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
- The constructor stores a name on the current object.
- Introduce receives the current object as self.
self.namereads that object’s own name.
first = Dog("Milo")
second = Dog("Luna")
second.introduce()Line-by-line explanation
- Two separate objects are created.
- Each has its own name.
- 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
- Show receives the current object.
- The desired attribute is title.
Hint
- Begin with
self. - Use a dot.
- Do not quote the attribute name.
Show Solution
class Book:
def show(self):
print(self.title)Line-by-line explanation
- Self refers to the current Book.
self.titlereads its attribute.- Print displays that value.