Design a Data Helper Class in Python
Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.
Python code
49 linesclass DataPoint:
def __init__(self, x, y):
self.x = x
self.y = y
self.label = None
def describe(self):
"""Return a human-readable description of the data point."""
base = f"DataPoint(x={self.x}, y={self.y})"
return f"{base}, label='{self.label}'" if self.label else base
class Dataset:
def __init__(self, name):
self.name = name
self.points = []
def add_point(self, x, y, label=None):
"""Add a new data point to the dataset."""
point = DataPoint(x, y)
point.label = label
self.points.append(point)
def summary(self):
"""Return dataset stats as a dictionary."""
if not self.points:
return {"name": self.name, "count": 0}
xs = [p.x for p in self.points]
ys = [p.y for p in self.points]
return {
"name": self.name,
"count": len(self.points),
"x_range": (min(xs), max(xs)),
"y_range": (min(ys), max(ys)),
}
def print_points(self):
"""Print all points to the console."""
for p in self.points:
print(p.describe())
if __name__ == "__main__":
ds = Dataset("Sample")
ds.add_point(1, 2, label="A")
ds.add_point(3, 5)
ds.add_point(0, 1, label="B")
ds.print_points()
print("Summary:", ds.summary())
Output
DataPoint(x=1, y=2), label='A'
DataPoint(x=3, y=5)
DataPoint(x=0, y=1), label='B'
Summary: {'name': 'Sample', 'count': 3, 'x_range': (0, 3), 'y_range': (1, 5)}
How it works
Two classes work together: DataPoint holds a single (x,y) coordinate plus an optional label, while Dataset manages a collection and provides operations like add_point, summary, and print_points. The __init__ method initializes instance attributes, and describe returns a readable string using an f-string with a conditional for the label. The summary method uses list comprehensions to compute min and max ranges. This pattern cleanly separates data storage from behavior, making it easy to extend later (e.g., add filtering).
Common mistakes
- Forgetting to pass `self` as the first parameter in methods.
- Mutating a point's label directly instead of using the `label` parameter in `add_point`.
- Assuming `summary` returns a string; it returns a dictionary.
- Not handling empty datasets before computing min/max.
Variations
- Use dataclasses for `DataPoint` to reduce boilerplate.
- Add a `__repr__` method to `DataPoint` for nicer debugging output.
Real-world use cases
- Storing and analyzing sensor readings where each reading has coordinates and annotations.
- Building a small feature store for machine learning where each sample has features and labels.
- Grouping plotting points for visualizations, with summaries of ranges and counts.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.