Sitemap

Member-only story

“Emulating Physical Units in Python Using Classes: A Mini Unit System”

2 min readJun 29, 2025

--

Press enter or click to view image in full size
Photo by Feliphe Schiarolli on Unsplash

🧠 Why This Matters

Have you ever written physics or engineering code in Python and accidentally mixed meters with seconds, or forgot to convert units? These kinds of bugs can be dangerous (looking at you, Mars Climate Orbiter 🛰️).

Let’s build a lightweight unit system in Python that allows you to perform operations like:

distance = 10 * meter
time = 2 * second
speed = distance / time
print(speed) # 5.0 m/s

This post will show how to:

  • Build a unit system using Python classes
  • Overload arithmetic operators
  • Provide clean unit-aware expressions

🛠️ Step-by-Step: Create a Custom Unit System

Step 1: Define the Unit Class

This class will hold both a numeric value and a string for the unit.

class Unit:
def __init__(self, value, unit):
self.value = value
self.unit = unit

def __repr__(self):
return f"{self.value} {self.unit}"

def __add__(self, other):
if self.unit != other.unit:
raise ValueError(f"Cannot add {self.unit} and {other.unit}")
return…

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers