Series Data Voyage Training Log

~1 min read

OOP Basics Through Classes

Grasping OOP, which bundles data (state) and function (behavior), through examples like Person, BankAccount, and Student, and learning classes, constructors, methods, and instance variables.

TrainingPythonOOP

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 value at 0 and increments it on each inc(), with independent state per instance
  • Rectangle returns area and perimeter via area() and perimeter()
  • BankAccount has deposit() and withdraw() plus guard logic that blocks withdrawal on insufficient balance
  • Student takes a score list and returns the mean via average()
  • Todo starts done as False and marks it complete via finish()

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.