Behavior lives in methods
A method is a function defined inside a class. It always takes self first, which is how it reaches the object's own attributes. You have been calling methods all along: "hi".upper() and my_list.append(3) from Python for Beginners are methods on str and list objects.
class Player: def __init__(self, name): self.name = name self.score = 0 def add_points(self, points): self.score += points
When you write mia.add_points(10), Python translates it to Player.add_points(mia, 10). That is the whole mystery of self: it is the object before the dot.
Code exercise · python
Run this program. The method updates the object it was called on and can use its other attributes.
Dict or class?
Both model "a thing with named parts". Use this rule:
| Situation | Reach for |
|---|---|
| Loose data passing through: records read from a file, configuration values, counting | dict |
| Data plus behavior and invariants (rules the data must always obey, like a balance never going negative) | class |
A class gives you three wins over the dict version:
- Typo safety:
mia.scorraisesAttributeErrorimmediately, whileplayer["scor"]silently creates a new key on assignment. - A home for logic:
add_pointslives next to the data it changes. - A contract: every
Playeris guaranteed to havenameandscore, because__init__sets them.
In unit 8 you will parse JSON, a text format for structured data defined there, into dicts, then convert the important pieces to objects at the boundary. That combination is everyday production Python.
Code exercise · python
Your turn. Add a deposit method and a withdraw method to Account. withdraw should subtract only if there is enough money, otherwise print "insufficient funds" and change nothing.
Code exercise · python
Your turn. Methods can answer questions as well as change state. Give Rectangle an area method returning width * height, and an is_square method returning True exactly when the sides match.
Quiz
mia.add_points(10) is equivalent to which call?