__init__ and Instance Attributes
Scenario: Every account must begin with a name and balance in a valid state.
New words, in plain English
- Initializer -
__init__, called after a new instance is created - Instance attribute - data belonging to one object
- Invariant - a rule that should always remain true
Initialize required state in __init__. Methods can enforce invariants rather than allowing callers to edit everything carelessly.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
Tip:__init__initializes an existing new instance;__new__actually creates it and is rarely overridden.
Goal: Practice this idea in the py-small-class challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.