Episode 17 of 29

The __init__ Function

Learn about the constructor method (__init__) for initializing object attributes.

The __init__ method is the constructor — it runs automatically when you create a new object.

Using __init__

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

    def introduce(self):
        print(self.name + " is a " + self.breed)

dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "German Shepherd")
dog1.introduce()  # Buddy is a Golden Retriever

self Keyword

self refers to the current instance of the class. It allows each object to have its own attributes.