Classes and Objects
What is it?
Object-Oriented Programming (OOP) is a software engineering paradigm that packages state (attributes) and related behavior (methods) into cohesive, reusable entities called objects:
- A Class serves as a structural blueprint defining how objects behave.
- An Instance is an allocated object created from that class with its own specific state.
__init__is the initializer method called when an instance is instantiated.selfexplicitly references the calling instance object, providing access to its unique namespace.
Motivating Architecture: The Scikit-Learn Estimator Pattern
All production machine learning frameworks are built around OOP principles. For example, Scikit-learn models inherit from common base classes exposing a uniform interface:
# The universal Machine Learning interface implemented via OOP:
model = RidgeRegression(alpha=0.1) # 1. Instantiate with hyperparameters
model.fit(X_train, y_train) # 2. Learn parameters from data (state update)
predictions = model.predict(X_test) # 3. Generate predictions using learned stateWhy we need it
In modern machine learning engineering:
- PyTorch Neural Networks: Every custom deep learning model subclasses
torch.nn.Module, initializing layers in__init__and defining execution inforward(). - Custom PyTorch Datasets: Inheriting from
torch.utils.data.Datasetrequires implementing magic methods__len__and__getitem__. - Callable Layers: Neural network layers act like functions because they implement the
__call__dunder method (output = layer(input)). - Clean Hyperparameter Encapsulation: Packaging models, data preprocessors, and evaluation metrics into classes keeps state tidy and eliminates risky global variables.
Explained in detail
1. Anatomy of a Python Class
class RidgeRegression:
# Class attribute: shared across ALL instances of this class
framework = "ML204-Core"
def __init__(self, alpha: float = 1.0):
# Instance attributes: unique to THIS specific instance
self.alpha = alpha
self.weights_ = None # Trailing underscore convention for learned state
self.bias_ = None
def fit(self, X, y):
"""Learns model weights from feature matrix X and target vector y."""
# Solves: w = (X^T X + alpha * I)^(-1) X^T y
print(f"Fitting model with regularization alpha={self.alpha}...")
self.weights_ = [0.25, -0.80]
self.bias_ = 0.05
return self # Return self to allow method chaining (model.fit().predict())
def predict(self, X):
"""Generates predictions using learned weights."""
if self.weights_ is None:
raise RuntimeError("Model is not fitted yet! Call .fit() first.")
return [sum(w * x for w, x in zip(self.weights_, row)) + self.bias_ for row in X]Think of a class as an automotive blueprint for an electric vehicle. The blueprint defines what an accelerator pedal does (methods) and where the battery sits. An instance is an actual car rolling off the factory line. Each physical car has its own battery charge level (self.battery_level), but all share the same acceleration logic.
2. Method Types: Instance, Class, and Static Methods
Python distinguishes between three kinds of methods using decorators:
class TransformerModel:
default_hidden_dim = 768
def __init__(self, hidden_dim: int, num_layers: int):
self.hidden_dim = hidden_dim
self.num_layers = num_layers
# 1. Instance Method: Receives 'self' (the specific instance)
def count_parameters(self) -> int:
return self.hidden_dim * self.num_layers * 12
# 2. Class Method: Receives 'cls' (the class itself) β ideal for factory constructors!
@classmethod
def from_pretrained(cls, model_size: str = "base"):
"""Alternative constructor loading preset configurations."""
if model_size == "large":
return cls(hidden_dim=1024, num_layers=24)
return cls(hidden_dim=cls.default_hidden_dim, num_layers=12)
# 3. Static Method: Plain utility function tied to the class namespace (no self or cls)
@staticmethod
def validate_tensor_shape(shape: tuple) -> bool:
return len(shape) == 3 and shape[0] > 0# Using the factory constructor:
large_model = TransformerModel.from_pretrained("large")
print("Hidden dim:", large_model.hidden_dim) # 10243. Encapsulation & Managed Attributes with @property
In Python, there are no true private keywords. Instead, encapsulation relies on conventions and property decorators:
_attribute(single underscore): Protected by convention (internal implementation detail, do not touch).__attribute(dunder prefix): Triggers Name Mangling (_ClassName__attribute) to prevent accidental override in subclasses.@property: Turns a method into a managed attribute with getter, setter, and validation logic:
class HyperparameterConfig:
def __init__(self, learning_rate: float):
self._learning_rate = None
self.learning_rate = learning_rate # Triggers setter validation!
@property
def learning_rate(self) -> float:
"""Getter: returns internal value."""
return self._learning_rate
@learning_rate.setter
def learning_rate(self, value: float):
"""Setter: validates input before assigning."""
if value <= 0:
raise ValueError(f"Learning rate must be strictly positive! Received {value}")
self._learning_rate = value
config = HyperparameterConfig(0.01)
print(config.learning_rate) # 0.01
# config.learning_rate = -0.5 # Raises ValueError: Learning rate must be strictly positive!4. Inheritance, super(), and Method Resolution Order (MRO)
Inheritance enables code reuse and polymorphism. Subclasses inherit capabilities from parent classes and call parent constructors via super():
class BaseNeuralLayer:
def __init__(self, in_features: int, out_features: int):
self.in_features = in_features
self.out_features = out_features
def forward(self, x):
raise NotImplementedError("Subclasses must implement forward()!")
class LinearLayer(BaseNeuralLayer):
def __init__(self, in_features: int, out_features: int, bias: bool = True):
# Call base class constructor
super().__init__(in_features, out_features)
self.has_bias = bias
def forward(self, x):
return f"Computing matrix product of shape ({self.in_features}, {self.out_features})"Method Resolution Order (MRO)
When resolving attributes in multiple inheritance, Python uses the C3 Linearization algorithm:
print(LinearLayer.__mro__)
# (<class 'LinearLayer'>, <class 'BaseNeuralLayer'>, <class 'object'>)5. Magic (Dunder) Methods in Machine Learning
Dunder (double underscore) methods allow user-defined objects to interact with Python built-ins like len(), [], (), and print():
Building a PyTorch-Style Dataset and Callable Layer
class TabularDataset:
def __init__(self, features, targets):
self.X = features
self.y = targets
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
class DenseNeuron:
def __init__(self, weights, bias):
self.weights = weights
self.bias = bias
# __call__ allows instance to be called directly like a function!
def __call__(self, x):
return sum(w * val for w, val in zip(self.weights, x)) + self.bias
# Testing the container and callable protocols:
data = TabularDataset([[1.0, 2.0], [3.0, 4.0]], [1, 0])
print(f"Dataset has {len(data)} samples.") # Uses __len__
sample_x, sample_y = data[0] # Uses __getitem__
neuron = DenseNeuron(weights=[0.5, -0.2], bias=0.1)
output = neuron(sample_x) # Uses __call__!
print("Neuron output:", output)6. Full Custom Scikit-Learn Transformer from Scratch
Let's assemble all these concepts into a production-grade feature normalizer:
class CustomStandardScaler:
"""Standardizes features by removing the mean and scaling to unit variance."""
def __init__(self, with_mean=True, with_std=True):
self.with_mean = with_mean
self.with_std = with_std
self.mean_ = None
self.scale_ = None
def fit(self, X):
"""Computes mean and standard deviation per column."""
n_samples = len(X)
n_features = len(X[0])
if self.with_mean:
self.mean_ = [sum(row[j] for row in X) / n_samples for j in range(n_features)]
else:
self.mean_ = [0.0] * n_features
if self.with_std:
self.scale_ = []
for j in range(n_features):
variance = sum((row[j] - self.mean_[j]) ** 2 for row in X) / n_samples
self.scale_.append(variance ** 0.5 if variance > 0 else 1.0)
else:
self.scale_ = [1.0] * n_features
return self
def transform(self, X):
"""Applies feature standardization."""
if self.mean_ is None or self.scale_ is None:
raise RuntimeError("Transformer is not fitted! Call .fit() first.")
return [
[(row[j] - self.mean_[j]) / self.scale_[j] for j in range(len(row))]
for row in X
]
def fit_transform(self, X):
"""Fits and transforms in a single pass."""
return self.fit(X).transform(X)
def __repr__(self):
return f"CustomStandardScaler(with_mean={self.with_mean}, with_std={self.with_std})"Quiz
π§©
Ready to test yourself?
4 questions Β· explanations shown after
Teach & Solidify
Teach This: Classes and Objects
Core Intuition
Classes encapsulate weights and algorithms into reusable blueprints; ML frameworks leverage @classmethod factories, @property guards, and dunder methods like __call__ and __getitem__.
Key Concepts to Explain
- 1Use `@classmethod` factory methods (like `Model.from_config()`) to provide clean alternative constructors.
- 2Use `@property` setters to validate hyperparameters (e.g. learning rate > 0) upon assignment.
- 3Implement `__len__` and `__getitem__` to integrate custom data containers seamlessly with PyTorch DataLoaders.
- 4Implement `__call__` so model and layer instances can be invoked cleanly as `predictions = model(features)`.
β οΈ What Most Students Get Confused About
Confusing class attributes with instance attributes: defining `class Model: weights = []` shares that single weights list across all model instances! Always initialize state in `__init__` as `self.weights = []`.
Explain Classes and Objects in your own words
Imagine you are explaining this idea to a friend or classmate with no math background. Writing it out forces your brain to bridge gaps in your intuition.
Resources & GitHub
Resources & Study Materials
Deepen your understanding with author-prepared study notes, derivation proofs, and curated educational lectures.
Official guide on implementing BaseEstimator, TransformerMixin, and fit/predict conventions.
Step-by-step tutorial on subclassing Dataset with __len__ and __getitem__ for deep learning pipelines.
Hands-on Jupyter notebook and Python scripts for OOP design patterns and custom model classes.
Mastered this concept?
Tick this box when you feel confident explaining it.
Topic Resources
Python_Classes_and_Objects_Reference.py
Python Script238 B Β· Modified Latest
Was this clear?