RUNLOCALAIv38
->Will it run?Best GPUCompareTroubleshootStartLearnPulseModelsHardwareToolsBench
Run check
RUNLOCALAI

Independently operated catalog for local-AI hardware and software. Hand-written verdicts. Source-cited claims. Reproducible commands when we have them.

OP·Eruo Fredoline
DIR
  • Models
  • Hardware
  • Tools
  • Benchmarks
TOOLS
  • Will it run?
  • Compare hardware
  • Cost vs cloud
  • Choose my GPU
  • Prompting kits
  • Quick answers
REF
  • All buyer guides
  • Learn local AI
  • Methodology
  • Glossary
  • Errors KB
  • Trust
EDITOR
  • About
  • Author
  • How we make money
  • Editorial policy
  • Contact
LEGAL
  • Privacy
  • Terms
  • Sitemap
MAIL · MONTHLY DIGEST
Get monthly local AI changes
Monthly recap. No spam.
DISCLOSURE

Some links on this site are affiliate links (Amazon Associates and other first-class retailers). When you buy through them, we earn a small commission at no extra cost to you. Affiliate links do not influence our verdicts — there are cards we rate highly that we don't have affiliate relationships with, and cards that sell well that we refuse to recommend. Read more →

© 2026 runlocalai.coIndependently operated
RUNLOCALAI · v38
  1. >
  2. Home
  3. /Learn
  4. /Courses
  5. /Python for AI — Zero to Useful
  6. /Ch. 19
Python for AI — Zero to Useful

19. Object-Oriented Python

Chapter 19 of 36 · 15 min
KEY INSIGHT

OOP's real value in AI code is encapsulating the fit/transform pattern that appears everywhere: preprocessors, feature extractors, vectorizers, model wrappers. Private attributes (with `_`) protect internal state from accidental misuse.

Object-oriented programming (OOP) in Python isn't about academic hierarchies—it's about organizing code that manages state and behavior. For AI tools, you constantly deal with models, configurations, and data loaders that benefit from encapsulation.

The basic pattern: group related data and functions into classes. A class is a blueprint; instances are actual objects with their own state.

class DataPreprocessor:
    def __init__(self, normalize=True, missing_strategy="mean"):
        self.normalize = normalize
        self.missing_strategy = missing_strategy
        self._fitted = False
    
    def fit(self, data):
        """Compute statistics needed for transformation."""
        self._mean = data.mean()
        self._std = data.std()
        self._fitted = True
        return self
    
    def transform(self, data):
        if not self._fitted:
            raise ValueError("Call fit() before transform()")
        if self.normalize:
            return (data - self._mean) / self._std
        return data
    
    def fit_transform(self, data):
        return self.fit(data).transform(data)

# Usage
preprocessor = DataPreprocessor(normalize=True)
cleaned_data = preprocessor.fit_transform(raw_data)

A few things to notice: self is how instance methods access their own data. The underscore prefix on _fitted, _mean, and _std signals these are internal details—not part of the public API. Python conventions let you express intent without syntax.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Create a MovingAverage class that accepts a window_size in __init__. Add a consume(value) method that updates an internal list and returns the current moving average. Add a reset() method. Instantiate it and process this list: [1, 2, 3, 4, 5] and print each average.

← Chapter 18
Reading API Responses
Chapter 20 →
Classes for AI Tools