Unit 12 · lesson
Methods Put Behavior With the Data
Core path: 25 minutes
How can an object do something with its own data?
Currently, our Player class only stores data. But players also have behavior.
Create a method
A method is a function that belongs to a class.
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def display(self):
print(f"{self.name}: {self.score}")
Call the method using dot notation:
player = Player("Nova", 850)
player.display() # Outputs: Nova: 850
Diagrams open at a readable shape-aware scale. Zoom or expand when you need more detail.
Add behavior
Objects can change their own state:
def add_score(self, points):
self.score += points
When you call player.add_score(100), self refers to player, and points is 100.
Keep related state synchronized
Suppose rank is based on score. If we add score but forget to update rank, the object's state becomes inconsistent.
def add_score(self, points):
self.score += points
self.rank = self.determine_rank()
Diagrams open at a readable shape-aware scale. Zoom or expand when you need more detail.
The object owns the rule connecting score and rank, protecting its own internal consistency.
Dictionary vs object
Dictionaries are great for simple data records (like API responses). Objects are great when data and rules belong strongly together. Neither automatically wins.
Diagrams open at a readable shape-aware scale. Zoom or expand when you need more detail.
Protecting rules (Invariants)
Methods can prevent bad data:
def drain_battery(self, amount):
self.battery -= amount
if self.battery < 0:
self.battery = 0
This protects a rule: battery cannot be negative.
Vocabulary lab
Flip the idea, not just the card
Explain the term before you reveal the back. Then compare your explanation with the definition, example, and warning.
Read all terms without animation
- Method
- A function associated with a class or object. Example: player.add_score(100) Do not confuse it with: An independent function.
- self
- A reference to the current object inside an instance method. Example: self.score += points Do not confuse it with: A global variable.
- Behavior
- Actions an object or component can perform. Example: Calculating rank or updating score. Do not confuse it with: State (the data).