Loading lessons...
The __init__ Method
The __init__ Method
__init__ is a special method that runs automatically when you create an object. It sets up the object's starting state.
What __init__ does
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) # John
print(p1.age) # 36
The arguments after self are passed when you create the object.
Why self?
self refers to the current object. It lets each object store its own data. Without it, the method couldn't reach the object's attributes.
Not all classes need __init__
class MyClass:
x = 5
This class has no __init__; its attribute is shared on the class.
Dunder methods
__init__ is a "dunder" (double underscore) method. Python uses these special names for magic behavior.
Object identity
The __str__ dunder controls how an object prints. Without it, printing shows a memory address.
TL;DR
__init__(self, ...)runs on object creation.selfrefers to the current object.- Use it to set initial attribute values.
- Dunder methods use double underscores.