__init__ — Easy Examples
Constructor; called when a new instance is created to initialize its attributes
Implementing __init__
Basic implementation of __init__ in a class.
python
class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def __str__(self): return f"{self.name} ({self.breed})" dog = Dog("Rex", "German Shepherd") print(dog) print(dog.name)
__init__ constructor; called when a new instance is created to initialize its attributes. Implementing it lets you customize how Python interacts with your objects.
__init__ in action
Seeing __init__ called by Python's built-in operations.
python
# How Python calls __init__ automatically class Demo: def __init__(self, value): self.value = value def __init__(self): print(f"__init__ was called!") return self d = Demo(42) # This triggers __init__: print(d)
Python automatically calls __init__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground