Bundling Scattered Data Together
Until now, variables and functions lived separately. A class bundles related data (state) and the functions that handle it (behavior) into one frame. Once this view clicked, the code got far tidier.
Constructors and Instance Variables
class Person:
def __init__(self, name):
# Receive the name when the object is created and store it on this object
self.name = name
def introduce(self):
print(f"I am {self.name}")
p = Person("Minsu")
p.introduce()__init__ is the constructor that runs once when an object is born. self points to "this object itself." The decisive moment was creating two instances and confirming their states are independent.
Classes in Practice
- Counter starts
valueat 0 and increments it on eachinc(), with independent state per instance - Rectangle returns area and perimeter via
area()andperimeter() - BankAccount has
deposit()andwithdraw()plus guard logic that blocks withdrawal on insufficient balance - Student takes a score list and returns the mean via
average() - Todo starts
doneas False and marks it complete viafinish()
Takeaway
Key point
The difference between before and after using classes showed up in questions like "where do we block an insufficient balance?" Keeping data and the rules about that data in one place, the code for handling edge cases naturally moved inside the class. The later work of turning data-collection code into functions and modules started here.