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.