A method is a function defined with a class and invoked through an object. It keeps an operation close to the data it uses, replacing a generic function-plus-data pairing with a domain-specific interface. section 9.0
From a function to a method
A procedural solution calculates a score with average(scores). A ScoreList object keeps the scores and exposes the same operation as scores.average(). The calculation is unchanged, but the caller no longer needs to track the data separately. class ScoreList: def __init__(self, scores): self.scores = scores def average(self): return sum(self.scores) / len(self.scores) scores = ScoreList([85, 95, 98, 87, 80, 92]) print(scores.average()) section 9.0
The first parameter conventionally named self identifies the instance on which the method was called. Python passes that instance automatically, while explicitly supplied arguments follow it. The name is conventional rather than reserved, but standard usage keeps code readable and compatible with developer tools. section 9.2
Methods connect ordinary class mechanics with object behavior:
- __init__ runs after an instance is created and assigns attributes such as self.flavor. section 9.2
- Python finds methods through attribute lookup: an instance is checked first, then its class, where the method is commonly defined. section 9.12
- Inherited methods provide shared behavior; subclasses can reuse a parent method with super() or replace it with their own implementation. section 9.15
class ScoreList():
def __init__(self, scores):
self.scores = scores
def average(self):
return sum(self.scores) / len(self.scores)
scores = ScoreList([85, 95, 98, 87, 80, 92])
print(f'The final score is {scores.average()}.')
Compare the complete function-based and method-based score calculations side by side. section 9.0
Practice methods by implementing:
- An Envelope with send, add_postage, and postage_needed methods, then a BigEnvelope variant with different postage rules. section 9.20
- A Phone with dial, a SmartPhone with run_app, and an iPhone that overrides dial while calling the parent implementation. section 9.20
- Animal classes whose attributes and string conversion produce a report for a zoo. section 9.26



















