When a new object needs initial data, define an __init__ method on its class. Calling the class constructor, such as Task("Laundry", "Wash clothes", 3), invokes __init__ to establish the instance’s initial state. section 8.1 section 8.1.2
Initialize a task
Define required arguments and assign them to the new instance. Give attributes that will change later a useful initial value: ```python class Task: def __init__(self, title, desc, urgency): self.title = title self.desc = desc self.urgency = urgency self.status = "created" self.tags = [] def complete(self): self.status = "completed" task = Task("Laundry", "Wash clothes", 3) print(task.status) # created task.complete() print(task.status) # completed ``` section 8.1.3
The first parameter, conventionally named self, refers to the instance being initialized. Python supplies it implicitly, so callers pass title, desc, and urgency—not a separate self argument. The name self is a convention, not a Python keyword. section 8.1.1 section 8.1.2
Object creation and initialization are distinct steps. In the usual custom-class construction process, __new__ creates the instance first; __init__ then receives that instance and sets its attributes. You typically do not need to implement __new__ yourself. section 10.2.1
class Task:
def __init__(self):
print(f"__init__ gets called, creating object at {id(self)}")
def __new__(cls):
new_task = object.__new__(cls)
print(f"__new__ gets called, creating object at {id(new_task)}")
return new_task
task = Task()
# output the following lines:
__new__ gets called, creating object at 140702458469952
__init__ gets called, creating object at 140702458469952
Trace the two calls and compare their printed object identities. section 8.1.1
Keep initialization predictable and readable:
- Identify the arguments needed to make an instance ready for use, and assign the corresponding attributes in __init__. section 8.1.2
- Initialize instance attributes in __init__, even when methods will update them later. Otherwise, accessing an attribute before its defining method runs can raise AttributeError. section 8.1.3
- Place __init__ before other methods so readers can quickly see the data an instance holds. section 8.1.5
- If a subclass needs the same initialization as its superclass, it need not override __init__. For customized initialization, override it and use super() to access the superclass constructor. section 8.5.6
For a data class, @dataclass can generate __init__ from annotated fields, reducing repetitive assignment code. Field defaults become initialization defaults; fields without defaults must come before fields with defaults. section 9.2.2 section 9.2.1












