Initialize Valid State with __init__
Core idea
When ordinary construction creates an instance, Python invokes __init__ to initialize it. The instance is supplied as self, followed by construction arguments. Assign required attributes here so later methods can rely on them. __init__ must return None; it initializes rather than returns the new object.
class Parcel: def __init__(self, weight): self.weight = weight
print(Parcel(6).weight)The constructor argument is stored on the instance.
Create separate lists
class Queue: def __init__(self): self.items = []
a = Queue()b = Queue()a.items.append("box")print(b.items)Each initialization evaluates a new list literal.
Intentional failure: reject negative capacity
class Shelf: def __init__(self, capacity): if capacity < 0: raise ValueError("negative capacity") self.capacity = capacity
Shelf(-1)The exception prevents the call from successfully returning a configured shelf.
Common mistake
Do not return self from init; a non-None return raises TypeError. Do not rely on assertions for validation of external inputs.
Practice
Create a Tank with a capacity and a starting level of zero. Reject negative capacity; try zero and a positive value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Initialize required attributes
Check your understanding of initialization.
What is printed?
class Box: def __init__(self, n): self.n = nprint(Box(8).n)What is printed?
class Box: def __init__(self): self.items = []a = Box()b = Box()a.items.append(2)print(b.items)Which exception is raised?
class Box: def __init__(self): return 2Box()When should a required nonnegative capacity be validated?